Look at this code:
if Input.is_action_pressed("ui_down"):
acceleration_player.y = player_speed
$Sprite.play("walk")
else:
$Sprite.play("stand")
I want you to focus on the else
branch:
if Input.is_action_pressed("ui_down"):
# ...
else:
$Sprite.play("stand")
It says that if you are not pressing the action "ui_down"
the animation will be "stand"
. In which case the rest of calls to play
do not matter.
I suppose a solution is to make most of these if
into elif
. But then you won't be able to combine vertical and horizontal input. Instead...
I want to encourage to separation of concerns. Let us separate the visuals which is what you care about:
if Input.is_action_pressed("ui_right"):
acceleration_player.x = player_speed
if Input.is_action_pressed("ui_left"):
acceleration_player.x = -player_speed
if Input.is_action_pressed("ui_up"):
acceleration_player.y = -player_speed
if Input.is_action_pressed("ui_down"):
acceleration_player.y = player_speed
# visuals
if abs(acceleration_player.x) < 0.00001 and abs(acceleration_player.y) < 0.00001:
$Sprite.play("stand")
else:
$Sprite.play("walk")
if acceleration_player.x < 0:
$Sprite.flip_h = true
else:
$Sprite.flip_h = false
Note: the reason I check abs(acceleration_player.x) < 0.00001
instead of acceleration_player.x == 0.0
is just in case the value does not hit 0.0
exactly due to floating point errors, which I don't know if they are possible or not in your code. I would have used is_zero_approx
in Godot 3.2 or newer.
I submit to your consideration to leave only the check for acceleration_player.x
in the conditional. In particular if "walk"
does not represent an appropriate animation for vertical motion.
By the way the second part can be more compact if you want:
$Sprite.flip_h = acceleration_player.x < 0