Question by
animeman0 · Mar 05, 2016 at 07:23 PM ·
c#2dmovementrigidbody2d
Player won't stop moving when key is released
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);
}
}
}
}
Comment
Best Answer
Answer by mahdiii · Mar 05, 2016 at 07:37 PM
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, Get$$anonymous$$eyDown fires the event when the key becomes pressed, and Get$$anonymous$$eyUp 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.