Help, idle animation plays even when i try to play a different animation

Godot Version

Godot 4.4.1

Question

Help, idle animation plays even when i try to play a different animation
How do I stop that from happening?
The code I have is this:
var direction = Input.get_axis(“ui_left”, “ui_right”)

if direction == -1:
get_node(“AnimatedSprite2D”).flip_h = true
velocity.x = max(velocity.x - acc, -SPEED)
elif direction == 1:
get_node(“AnimatedSprite2D”).flip_h = false
velocity.x = min(velocity.x + acc, SPEED)

if Input.is_action_just_released(“ui_left”):
velocity.x = min(velocity.x - acc, SPEED)
elif Input.is_action_just_released(“ui_right”):
velocity.x = min(velocity.x + acc, SPEED)

if direction:
print(“true”)
if velocity.y== 0:
print(“pluh”)
$AnimationPlayer.play(“run loop”)
else:
print(“false”)
velocity.x = move_toward(velocity.x, 0, SPEED)
if velocity.y == 0:
$AnimationPlayer.play(“idle”)
if velocity.y > 0:
$AnimationPlayer.play(“Fall”)

move_and_slide()
If you see any other issues as well please point them out

Please add three backticks (```) before and after any code you post. This preserves formatting.

The posted script is incomplete, but I assume it’s all part of the _process or _physics_process method. Your problem probably is this line of code:

Based on how you only get input from ui_left and ui_right, it seems like you might be working on a platformer game or something similar. This line of code essentially says ‘if the player is not moving up or down, then the player must be idling’. Which isn’t always true. You could be moving purely to the right or left without moving up or down. In that case, you shouldn’t play the ‘idle’ animation, but the ‘run’ animation.

The quick fix is to only set the idle animation in case velocity in both x and y direction is 0. The better solution is to search the internet for ‘character controller state machine godot’ and implement your controller as a state machine.