Having trouble with playing animation based on direction

Godot Version

extends CharacterBody2D

var speed = 450
var player_state

func _physics_process(delta):
var direction = Input.get_vector(“left”, “right”, “up”, “down”)

velocity = speed * direction
move_and_slide()

play_animation(direction)

func play_animation(direction):
if direction.x == 0 and direction.y == 0:
player_state = “idle”

if player_state == "idle":
	$Sprite2D.play("idle")

if direction.x == 1 and direction.y == 0:
	player_state == "e-walk"

if player_state == "e-walk":
	$Sprite2D.play("e-walk")

if direction.x < 0 and direction.y == 0:
	player_state == "w-walk"

if player_state == "w-walk":
	$Sprite2D.play("w-walk")

Question

My player is able to walk and plays the idle animation, but I want it to play a walking animation when the character is moving left or right. However, the character is not doing so. I tried changing $Sprite2D to $AnimatedSprite2D however, it is still not working.

The first thing I will do is to use the _input(event) function to drive the animation. With the way your code is setup with play_animation() called every step in the physics process, it may mess up with your animation system where an animation is called multiple times and restarts the animation.

Also, do you use the up and down button for movement? If not, I’ll assume your game is a side scroller, so I will discard the direction.y to make the code simpler.

extends CharacterBody2D

var speed = 450

func _input(event):
        ##If left or right is pressed, it plays the relevant walk animation
	if Input.is_action_just_pressed("left"):
             $Sprite2D.play("w-walk")
	elif Input.is_action_just_pressed("right"):
             $Sprite2D.play("e-walk")

        ##Plays the idle animation once the left or right button is released
	if Input.is_action_just_released("left") or Input.is_action_just_released("right"):
             $Sprite2D.play("idle")

func _physics_process(delta):
        var direction = Input.get_vector(“left”, “right”, “up”, “down”)
        velocity = speed * direction
        move_and_slide()

Another suggestion is to just flip your sprite instead of having two different walk animations for left and right, this only works if both animations are similar.

There may be errors in the code since I did not test it, let me know if it works.

Wow. I fully understand all that code, thank you so much for the solution it works now.

1 Like

You’re welcome

You may have it sorted out already, but note that a single ‘=’ is for assigning a value. ‘==’ is for a boolean comparison.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.