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.
Yes, it is part of _physics_process(delta). I can submit the full code if that helps. I’ll try to implement it a different way, and I’ll share the results.
So, as it turns out, $AnimationPlayer.play(“run loop”) was configured to the $AnimatedSprite2d(“idle”), so the code was fine, but just in case, I changed it to this
if direction == 1 or direction == -1:
print("true")
if velocity.y == 0:
print("pluh")
$AnimationPlayer.play("run loop")
else:
print("flase")
velocity.x = move_toward(velocity.x, 0, SPEED)
if velocity.y == 0 and velocity.x == 0:
$AnimationPlayer.play("idle")
if velocity.y > 0:
$AnimationPlayer.play("Fall")
A new issue has appeared. I have Animated Sprite 2D linked to Animation Player, and for some reason the run animation (now known as running) grabs from Animated Sprite 2D idle even when I switch it to be connected to running. This may not be a new issue and is probably what was causing the first one.
I’ve figured it out: you need to add a key of the animated sprite at the beginning, then it will be used for the rest.