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.
If up and left are held at the same time, the script will play the left animation and then the topleft animation every frame, which resets the animation.
I can think of two possible solutions for this problem; you can get an input vector and set the animation based on the angle, or you can choose an animation for every possible input combination.
Choosing the animation based on the direction of an input vector:
const ANIMATION_NAMES = [
"right", "downright", "down", "downleft",
"left"…
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
system
Closed
July 9, 2024, 4:00pm
5
This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.