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);
}
}
}
}
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.
– rorydriscollThanks both of you!
– animeman0