[ad_1]
The downside could be extra apparent if we regulate 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 motion to the precise is totally separated from the case that checks to the left?
So let’s step by way of this code for a body when h > 0:
-
We hit the primary
ifand cross the take a look at, so we enter the block. -
Inside this
ifblock,"WalkParam"will get set totrue. -
We resume execution on the finish of the primary
if‘s block, because it has no connectedelse iforelseblocks to skip over. -
We hit the second
ifand fail the take a look at, so we skip to theelseblock. -
Inside this
elseblock,"WalkParam"will get set tofalse.
So we end this operate with WalkParam set to false.
You can repair this by altering your second if to an else if, so it is solely executed if the primary if take a look at fails, and skipped in any other case. That joins the total if–else if–else into one chain, the place precisely considered one of their contained blocks might be executed. Without this becoming a member of key phrase, every if might be checked impartial of the earlier take a look at’s consequence.
But you’ll be able to truly do all this way more merely:
// Use approximate comparisons for floats,
// in case of small rounding errors
if (Mathf.Approximately(h, 0)) {
animator.SetBool("WalkParam", false);
} else {
// Use one department for each stroll instructions.
// Less repetition = fewer locations for bugs.
float step = Mathf.Sign(h) * pace * Time.deltaTime;
rework.Translate(step, 0, 0, Space.World);
animator.SetBool("WalkParam", false);
sr.flipX = h < 0;
}
[ad_2]