🔍

simple Arduino Joystick to Unity via Joystick.h

Arduino joystick code


#include <Arduino.h>

#include "Joystick.h" // use this library to be a joystick

// Create Joystick
Joystick_ Joystick;

// -----------------------

// This sketch shows the basic operation of the Thumb Joystick (COM-09032) and breakout board (BOB-09110).
// The joystick outputs two analog voltages (VERT and HORIZ), and one digital signal (SEL) for the pushbutton.
 
const int VERT = 0; // analog
const int HORIZ = 1; // analog
const int SEL = 2; // digital
 
//initialize variables for analog and digital values
int vertical, horizontal, select;

void setup(){
 
// make the SEL pin an input
  pinMode(SEL, INPUT_PULLUP);

  // set up serial port for output
  //Serial.begin(9600);
}

void loop(){

  // read all values from the joystick
  vertical = analogRead(VERT); // will be 0-1023
  horizontal = analogRead(HORIZ); // will be 0-1023
  select = digitalRead(SEL); // will be HIGH (1) if not pressed, and LOW (0) if pressed

  //put new joystick data to joystick objrect and send
    Joystick.setXAxis(vertical);
    Joystick.setYAxis(horizontal);
     
    Joystick.setButton(3,select-1);
    Joystick.sendState();

  delay(10);

  return;

    // print out the values
  Serial.print("vertical: ");
  Serial.print(vertical, DEC);
  Serial.print(" horizontal: ");
  Serial.print(horizontal, DEC);
  Serial.print(" select: ");
  if (select == HIGH) {
    Serial.println("not pressed");
  }
  else {
    Serial.println("PRESSED!");
  }
delay(100);

}

Unity simple joystick controller to object


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class joystick_controller : MonoBehaviour
{
   
   public GameObject tgo;
   public Rigidbody rb_tgo;

   public float jumpforceII = 100f;
   public float moveSpeed = 50f;
   
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {


       
//Define the speed at which the object moves.

if( Input.GetButtonDown("Jump")  ){

    
    rb_tgo.AddForce(new Vector3(0,jumpforceII,0), ForceMode.Impulse);

}



float horizontalInput = Input.GetAxis("Horizontal");
//Get the value of the Horizontal input axis.

float verticalInput = Input.GetAxis("Vertical");
//Get the value of the Vertical input axis.

tgo.transform.Translate(new Vector3(horizontalInput, 0, verticalInput) * moveSpeed * Time.deltaTime);
//Move the object to XYZ coordinates defined as horizontalInput, 0, and verticalInput respectively.


    }
}