- Home /
How to get analog stick to work ?
Hi, I'm trying to make a game playable with joysticks and I cant manage to make it work. So Here is what I wrote :
temp = Input.GetAxis("Horizontal");
rb = GetComponent<Rigidbody2D>();
rb.velocity = new Vector2(speed * temp, 0);
This works well for the Xaxis but then I try to add the Yaxis by writing this :
temp2 = Input.GetAxis("Vertical");
rb = GetComponent<Rigidbody2D>();
rb.velocity = new Vector2(0, speed * temp2);
Then the character will only move on the Yaxis. So now if anyone have any idea I would highly appreciate,Thanks.
Comment
Best Answer
Answer by ASPePeX · Feb 15, 2017 at 08:45 AM
You are overwriting the Xaxis velocity with 0 on your last line.
This should work:
temp = Input.GetAxis("Horizontal");
temp2 = Input.GetAxis("Vertical");
rb = GetComponent<Rigidbody2D>();
rb.velocity = new Vector2(speed * temp, speed * temp2);
But allow me to optimize this a little bit more. No calling GetComponent() and not creating a new vector instance every frame, as well as using Time.deltaTime to make the movement independent from the framerate:
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
public class Movement : MonoBehaviour
{
public float speed = 10;
private Rigidbody2D rb;
private Vector2 movementVector;
void Start()
{
rb = GetComponent<Rigidbody2D>();
movementVector = Vector2.zero;
}
void Update()
{
movementVector.x = Input.GetAxis("Horizontal");
movementVector.y = Input.GetAxis("Vertical");
rb.velocity = movementVector * speed * Time.deltaTime;
}
}