7 Player Animation Adding different states

Here we will add different animations to player, simply use different frame animation based on the state of the player

We start by Adding different Animations

  • hit
  • idle
  • jump
  • walk

Then in the _physics_process, we show different state based on the player position and state

Like if the player is on the floor and if this player was hit, set it to false (indicating that the hit is completed)

Also when the player is on the floor, if there is no velocity, we will show the idle state, but if its moving we will show the walk animation.

	if is_on_floor():
		if is_hit:
			is_hit = false;
			
		if velocity.x != 0:
			animated_sprite_2d.play("walk")
		else:
			animated_sprite_2d.play("idle")

When the Player is not in the floor, we will show jump animation, and if was hit, we will show hit one.

	if not is_on_floor():
		velocity.y += gravity * delta
		if is_hit:
			animated_sprite_2d.play("hit")
		else:
			animated_sprite_2d.play("jump")

Based on the direction the user pressed last, we will face the player in that direction with the flip_h property.

		var direction = Input.get_axis("ui_left", "ui_right")
		if direction:
			velocity.x = direction * SPEED
			if direction -1:
				animated_sprite_2d.flip_h = true
			else:
				animated_sprite_2d.flip_h = false

We ignore the direction events from player, if we are hit, so when a Player is hit, we can't control it.

	if !is_hit:
		var direction = Input.get_axis("ui_left", "ui_right")
		if direction:
			velocity.x = direction * SPEED
			if direction -1:
				animated_sprite_2d.flip_h = true
			else:
				animated_sprite_2d.flip_h = false
		else:
			velocity.x = move_toward(velocity.x, 0, SPEED)

This could introduce a case where a player will be bounced back and forth among two obstracles and players can't interact at all. Warned you :)

When the player got hit, we call the move_and_slide() in that function itself and not wait till next _physic_process(delta), this is to avoid the is_floor check. There could be better ways to handle it but, for not let it be.

func hit(direction):
	is_hit = true
	velocity.y = JUMP_VELOCITY
	velocity.x = direction * SPEED
	
	move_and_slide()
	
	pass