Move_and_slide + animation not working

Godot Version

Question

I am trying to move a CharacterBody2D with an AnimatedSprite2D child node using the arrow keys. The character moves just fine and the first frame of the correct animation for the direction it is moving shows, but the rest of the animation doesn’t play. The animation worked fine until I added move_and_slide() to the CharacterBody2D. Thanks for any ideas. Here is my code:

CharacterBody2D code

extends CharacterBody2D

@export var speed = 200

func get_input():
	var input_direction = Input.get_vector("left", "right", "up", "down")
	velocity = input_direction * speed

func _physics_process(delta):
	get_input()
	move_and_slide()

AnimatedSprite2D code

extends AnimatedSprite2D


func get_input():
	if Input.is_action_pressed("ui_right"):
		play("walk_rt")
	else:
		stop()
	if Input.is_action_pressed("ui_left"):
		play("walk_l")
	else:
		stop()
	if Input.is_action_pressed("ui_up"):
		play("walk_u")
	else:
		stop()
	if Input.is_action_pressed("ui_down"):
		play("walk_d")
	else:
		stop()
		
func _physics_process(delta):
	get_input()

Try to imagine, what the code does if you’re holding “ui_up”, for example. It’ll call stop(), stop(), play("walk_u") and then stop() every frame.

I’ve previously written code examples for playing animations for 8-way movement, which could give you some ideas on how to solve the problem.

Do like this:

func get_input():
	if Input.is_action_pressed("ui_right"):
		play("walk_rt")
	elif Input.is_action_pressed("ui_left"):
		play("walk_l")
	elif Input.is_action_pressed("ui_up"):
		play("walk_u")
	elif Input.is_action_pressed("ui_down"):
		play("walk_d")
	else:
		stop()

Here we added elif

Thanks. I guess that should have been obvious. It’s working now.

1 Like