0
\$\begingroup\$

I have created two animations: "Walk" and "Idle" and I made the transitions from "Idle" to "Walk" and from "Walk" to "Idle" as well.

When I go the the left side, the "Walk" animation is being played, but when I go to the right, the animation doesn't play.

Here is my Movement Function:

void PlayerMovement()
{
    tempPos = transform.position;
    float h = Input.GetAxisRaw("Horizontal");

    if (h > 0)
    {
        //tempPos.x += speed * Time.deltaTime;
        animator.SetBool("WalkParam", true);
        //sr.flipX = false;

    }
    if (h < 0)
    {
        //tempPos.x -= speed * Time.deltaTime;
        animator.SetBool("WalkParam", true);
        //sr.flipX = true;
    }
    else
    {
        animator.SetBool("WalkParam", false);
    }
    transform.position = tempPos;
}
\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

The problem might be more obvious if we adjust the whitespace in your code like so:

if (h > 0) {
    animator.SetBool("WalkParam", true);
}

if (h < 0) {
    animator.SetBool("WalkParam", true);
} else {
    animator.SetBool("WalkParam", false);
}

See how the case that checks for movement to the right is completely separated from the case that checks to the left?

So let's step through this code for a frame when h > 0:

  1. We hit the first if and pass the test, so we enter the block.

  2. Inside this if block, "WalkParam" gets set to true.

  3. We resume execution at the end of the first if's block, since it has no attached else if or else blocks to skip over.

  4. We hit the second if and fail the test, so we skip to the else block.

  5. Inside this else block, "WalkParam" gets set to false.

So we finish this function with WalkParam set to false.

You can fix this by changing your second if to an else if, so it's only executed if the first if test fails, and skipped otherwise. That joins the full if-else if-else into one chain, where exactly one of their contained blocks will be executed. Without this joining keyword, each if will be checked independent of the previous test's outcome.

But you can actually do all this much more simply:

// Use approximate comparisons for floats,
// in case of small rounding errors
if (Mathf.Approximately(h, 0)) {
    animator.SetBool("WalkParam", false);
} else {
    // Use one branch for both walk directions.
    // Less repetition = fewer places for bugs.
    float step = Mathf.Sign(h) * speed * Time.deltaTime;
    transform.Translate(step, 0, 0, Space.World);
    animator.SetBool("WalkParam", false);
    sr.flipX = h < 0;
}
\$\endgroup\$
2
  • \$\begingroup\$ Thank you. I found that it was missing "else if". Instead, I had written just "if". So, the problem is solved. \$\endgroup\$ Nov 5, 2022 at 13:41
  • 1
    \$\begingroup\$ Yes, that's what I said. \$\endgroup\$
    – DMGregory
    Nov 5, 2022 at 13:42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .