Reputation: 29
I'm making a game where i simply has to use a virtuel joystick instead of WASD. Everything i've done didn't work, i could really use some help. My code for now is this:
private void Update()
{
Rigidbody rb = GetComponent<Rigidbody>();
if (Input.GetKey(KeyCode.A))
rb.AddForce(Vector3.left);
if (Input.GetKey(KeyCode.D))
rb.AddForce(Vector3.right);
if (Input.GetKey(KeyCode.W))
rb.AddForce(Vector3.forward);
if (Input.GetKey(KeyCode.S))
rb.AddForce(Vector3.back);
}
However, i've also writtin this code:
float moveHorizontal = joystick.Horizontal;
float moveVertical = joystick.Vertical;
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.AddForce(movement * speed * Time.deltaTime);
I already have a joystick and i saw in a YT video that he uses joystick.Horizontal. I want the W key for example to be, if joystick goes up move forward or something like that. Thank you for your time :)
Upvotes: 0
Views: 345
Reputation: 3719
Your first code should work, but the amount of force you add is probably too small for you to see it move.
Try multiplying it by some value like: rb.AddForce(Vector3.forward*50);
Even if it works, you should know that it is not very optimized. For example, you should not get the Rigidbody in every update, try something like:
public float speed = 50f;
private Rigidbody rb;
void Awake() {
rb = GetComponent<Rigidbody>();
}
private void Update() {
if (Input.GetKey(KeyCode.A))
rb.AddForce(Vector3.left * speed);
if (Input.GetKey(KeyCode.D))
rb.AddForce(Vector3.right * speed);
if (Input.GetKey(KeyCode.W))
rb.AddForce(Vector3.forward * speed);
if (Input.GetKey(KeyCode.S))
rb.AddForce(Vector3.back * speed);
}
Finally for those who are more familiar with Unity, I encourage you to use the New Input System.
Upvotes: 2