Why I can't see a completed attacking animation in MonoGame?

Hi, everyone,
I have a question about animation in MonoGame, please look at the following code, all other animations are OK in test, but the Attack animation is wrong, the attack animation has 3 frames, but usually I can only see it can play 1 frame or 2 frames, maybe my code has some problems, Could you tell me how to deal with the problem?

enum Animations
{
    Idle,
    Run,
    Jump,
    Fall,
    Attack
}

public void update()
{
    var moveDir = new Vector2(_xAxisInput.value, 0);

    if (moveDir.X > 0)
    {
	if (!_collisionState.below)
	{
	    animation = Animations.Jump;
	}
	else
	{
	    animation = Animations.Run;
	}

	_animation.flipX = false;
	_velocity.X = moveSpeed;
    }
    else if (moveDir.X < 0)
    {
	if (!_collisionState.below)
	{
	    animation = Animations.Jump;
	}
	else
	{
	    animation = Animations.Run;
	}
	_animation.flipX = true;
	_velocity.X = -moveSpeed;
    }
    else
    {
	_velocity.X = 0;
	if (_collisionState.below)
	{
	    animation = Animations.Idle;
	}
    }

    //jump
    if (_collisionState.below && _jumpInput.isPressed)
    {
	animation = Animations.Jump;
	_velocity.Y = -Mathf.sqrt(2.0f * jumpHeight * gravity);
    }

    //falling
    if (!_collisionState.below && _velocity.Y > 0)
	animation = Animations.Fall;

    //attack
    if (_attackInput.isPressed)
    {
	animation = Animations.Attack;                
    }

    //apply gravity
    _velocity.Y += gravity * Time.deltaTime;

    var deltaMove = _velocity * Time.deltaTime;

    //move
    _mover.move(deltaMove, _boxCollider, _collisionState);

    if (_collisionState.below)
	_velocity.Y = 0;

    if (!_animation.isAnimationPlaying(animation))
    {
	_animation.play(animation);
    }
} 
else
{
    _velocity.X = 0;
    if (_collisionState.below)
    {
	animation = Animations.Idle;
    }
}

If collisionState.below is true even while attacking, it’ll switch to the idle animation here. You want to not do this if your character is attacking.

To make this more manageable, I suggest looking into finite state machines. The article gets fairly complicated, but I recommend reading halfway into it. Essentially, you’d write your character controller so your character is in only one state at a time. This way lets you perform certain actions and play certain animations only when each state allows it, preventing you from breaking your code whenever you add a new action your character can perform.

1 Like

thank you so much!! that’s really what I need :slight_smile: