unity joystick controls code example
Example 1: unity mobile controls
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour {
public float moveSpeed = 300;
public GameObject character;
private Rigidbody2D characterBody;
private float ScreenWidth;
void Start () {
ScreenWidth = Screen.width;
characterBody = character.GetComponent<Rigidbody2D>();
}
void Update () {
int i = 0;
while (i < Input.touchCount) {
if (Input.GetTouch (i).position.x > ScreenWidth / 2) {
RunCharacter (1.0f);
}
if (Input.GetTouch (i).position.x < ScreenWidth / 2) {
RunCharacter (-1.0f);
}
++i;
}
}
void FixedUpdate(){
#if UNITY_EDITOR
RunCharacter(Input.GetAxis("Horizontal"));
#endif
}
private void RunCharacter(float horizontalInput){
characterBody.AddForce(new Vector2(horizontalInput * moveSpeed * Time.deltaTime, 0));
}
}
Example 2: unity 2d joystick controls
public Joystick joystick;
private Vector3 input;
public float Speed = 5f;
private void Update()
{
input = new Vector3(joystick.Horizontal, joystick.Vertical);
Vector3 velocity = input.normalized * Speed;
transform.position += velocity * Time.deltaTime;
}