Player won't stop moving when key is released (160430)

As it says in the title player won’t stop moving when key is released and I can’t figure out why.
using UnityEngine;
using System.Collections;

public class Controller : MonoBehaviour {

	public float Speed = 5f;
	Rigidbody2D rb;
	// Use this for initialization
	void Start () {
		rb = GetComponent<Rigidbody2D> ();

	}

	void FixedUpdate () {

		if (Input.GetKeyDown (KeyCode.W)) 
		{
			rb.velocity = new Vector2 (rb.velocity.x, Speed);
			if (Input.GetKeyUp (KeyCode.W)) 
			{
				rb.velocity = new Vector2 (0,0);
			}
		}
		if (Input.GetKeyDown (KeyCode.S)) 
		{
			rb.velocity = new Vector2 (rb.velocity.x, Speed * -1);
			if (Input.GetKeyUp (KeyCode.S)) 
			{
				rb.velocity = new Vector2 (0,0);
			}
		}
		if (Input.GetKeyDown (KeyCode.A)) 
		{
			rb.velocity = new Vector2 (Speed * -1,rb.velocity.y);
			if (Input.GetKeyUp (KeyCode.A)) 
			{
				rb.velocity = new Vector2 (0,0);
			}
		}
		if (Input.GetKeyDown (KeyCode.D)) 
		{
			rb.velocity = new Vector2 (Speed, rb.velocity.y);
			if (Input.GetKeyUp (KeyCode.D)) 
			{
				rb.velocity = new Vector2 (0,0);
			}
		}
	}
}

1 Answer

1

you wrote two if into together. It is incorrect
if(){
if(){
}
}
you must write as:
if (Input.GetKeyDown (KeyCode.W))
{

}
if (Input.GetKeyUp (KeyCode.W))
{
rb.velocity = new Vector2 (0,0);
}
Also you must do the same work for others.

To be clear, GetKeyDown fires the event when the key becomes pressed, and GetKeyUp is fired when it is released. These can't be both true so the inner if can never be hit. Pull out your inner if statements to the FixedUpdate body.

Thanks both of you!