Reputation: 11
I made a unity program in C# in which the player can move and jump.
When I run the code the player's idle animation
and the player's jumping animation
both play at the same time in the animator causing a glitch and it doesn't look that good.
Here's the code which I used:
if (Input.GetKey("d") || Input.GetKey("right"))
{
rb2D.velocity = new Vector2(Forwardspeed, 0f);
animator.Play("Player_run");
spr.flipX = false;
}
else if (Input.GetKey("a") || Input.GetKey("left"))
{
rb2D.velocity = new Vector2(-Forwardspeed, 0f);
animator.Play("Player_run");
spr.flipX = true;
}
else if (!Input.anyKeyDown)
{
rb2D.velocity = new Vector2(0, 0);
animator.Play("Player_idle");
}
else if (Input.GetKey("space"))
{
rb2D.velocity = new Vector2(Forwardspeed, Uppwardforce);
animator.Play("Player_jump");
}
Upvotes: 1
Views: 118
Reputation: 9
Based around your code design, why not use the idle as an else condition? This way if you don't have a key down, your player will just idle. eg:
if (Input.GetKey("d") || Input.GetKey("right"))
{
rb2D.velocity = new Vector2(Forwardspeed, 0f);
animator.Play("Player_run");
spr.flipX = false;
}
else if (Input.GetKey("a") || Input.GetKey("left"))
{
rb2D.velocity = new Vector2(-Forwardspeed, 0f);
animator.Play("Player_run");
spr.flipX = true;
}
else if (Input.GetKeyDown("space"))
{
rb2D.velocity = new Vector2(Forwardspeed, Uppwardforce);
animator.Play("Player_jump");
}
else
{
rb2D.velocity = new Vector2(0, 0);
animator.Play("Player_idle");
}
Hope this helps.
Upvotes: 1
Reputation: 17007
why dont do that:
else if (Input.GetKey("a") || Input.GetKey("left"))
{
rb2D.velocity = new Vector2(-Forwardspeed, 0f);
animator.Play("Player_run");
spr.flipX = true;
if (Input.GetKey("space"))
{
rb2D.velocity = new Vector2(Forwardspeed, Uppwardforce);
animator.Play("Player_jump");
}
}
if you dont need to add force you could just test the KeyDown
if (Input.GetKeyDown("space"))
{
rb2D.velocity = new Vector2(Forwardspeed, Uppwardforce);
animator.Play("Player_jump");
}
You hold the key "run" down and you just pulse the key space
Upvotes: 0