Hey there! So I made a top-down character controller using RigidBody2D, and it works pretty well, but I’ve noticed that if I hold down say A and W, and then release the button I held down second, that second button’s animation continues playing. Is there any way to fix this?
playerController.cs
void Update()
{
//Moving Left
if (Input.GetKeyDown(KeyCode.A))
{
anim.Play("walk-left");
horizontal += -5;
direction = 4;
this.GetComponent<Rigidbody2D>().velocity = new Vector2(horizontal, vertical);
}
else if (Input.GetKeyUp(KeyCode.A))
{
horizontal += 5;
this.GetComponent<Rigidbody2D>().velocity = new Vector2(horizontal, vertical);
}
//Moving Right
if (Input.GetKeyDown(KeyCode.D))
{
anim.Play("walk-right");
horizontal += 5;
direction = 2;
this.GetComponent<Rigidbody2D>().velocity = new Vector2(horizontal, vertical);
}
else if (Input.GetKeyUp(KeyCode.D))
{
horizontal += -5;
this.GetComponent<Rigidbody2D>().velocity = new Vector2(horizontal, vertical);
}
//Moving Up
if (Input.GetKeyDown(KeyCode.W))
{
vertical += 5;
anim.Play("walk-up");
direction = 1;
this.GetComponent<Rigidbody2D>().velocity = new Vector2(horizontal, vertical);
}
else if (Input.GetKeyUp(KeyCode.W))
{
vertical += -5;
this.GetComponent<Rigidbody2D>().velocity = new Vector2(horizontal, vertical);
}
//Moving Down
if (Input.GetKeyDown(KeyCode.S))
{
anim.Play("walk-down");
vertical += -5;
direction = 3;
this.GetComponent<Rigidbody2D>().velocity = new Vector2(horizontal, vertical);
}
else if (Input.GetKeyUp(KeyCode.S))
{
vertical += 5;
this.GetComponent<Rigidbody2D>().velocity = new Vector2(horizontal, vertical);
}
if (this.GetComponent<Rigidbody2D>().velocity.magnitude <= 0)
{
if (direction == 1)
{
anim.Play("idle-up");
}
if (direction == 2)
{
anim.Play("idle-right");
}
if (direction == 3)
{
anim.Play("idle-down");
}
if (direction == 4)
{
anim.Play("idle-left");
}
}
}