I'm working on a simple 2D platformer with animation and I managed to get the animation state machine to work with just one problem, the falling animation won't work when falling off of an edge, it only gets triggered after the jumping animation.
private void AnimationState()
{
if (state == State.jumping)
{
if (rb.velocity.y < .1f)
{
state = State.falling;
}
}
else if (state == State.falling)
{
if (isGrounded == true)
{
state = State.idle;
}
}
else if (state == State.hurt)
{
if (Mathf.Abs(rb.velocity.x) < .1f)
{
state = State.idle;
}
}
else if (Mathf.Abs(rb.velocity.x) > 2f)
{
state = State.running;
}
else
{
state = State.idle;
}
}
If the sprite slows down below 2f in the X direction, it will enter the idle state. Then once in the idle state, your logic will only be able to transition into running. If it falls of the edge, there is nothing in your code to transition it into the falling state.
You should not write the state machine like that where you specify every possible transition from each state to each other state as there are N squared permutations. Instead, you should identify the state without caring what the current state is.
For example: