Mild_Sauce
Mild_Sauce

Reputation: 11

Animations running at the same time

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

Answers (2)

Clive Alford
Clive Alford

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

Frenchy
Frenchy

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

Related Questions