How do I stop the animation when direction input stops

Godot Version

4.3

This is my first time coding; my characters animations are working in all directions, but they won’t go to “Idle” and I’m not sure what to input for it

my code.

extends CharacterBody2D

@export var speed = 400
@onready var animated_sprite = $AnimatedSprite2D
var input: Vector2

func _process(_delta):
if Input.is_action_just_pressed(“right”):
animated_sprite.play(“Walk_Right”)
if Input.is_action_just_pressed(“left”):
animated_sprite.play(“Walk_Left”)
if Input.is_action_just_pressed(“up”):
animated_sprite.play(“Walk_Up”)
if Input.is_action_just_pressed(“down”):
animated_sprite.play(“Walk_Down”)

func _ready() → void:
animated_sprite.play(“Idle”)

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

func _physics_process(delta: float) → void:
get_input()
move_and_slide()

Firstly, just a tip: you can format code to make it easier to read by highlighting it all and pressing Ctrl+e.

I assume you have an “Idle” animation which isn’t playing when there is no input. In your _process() function you aren’t handling no input. You can add an else: block to your if statement to catch any input which doesn’t match the previous if blocks:

else:
        animated_sprite.play(“Idle”)

You will want to change the if blocks to elif, except the first one. This keeps all the input tests in one if/else/elif block:

func _process(_delta):
    if Input.is_action_just_pressed(“right”):
        animated_sprite.play(“Walk_Right”)
    elif Input.is_action_just_pressed(“left”):
        animated_sprite.play(“Walk_Left”)
    elif Input.is_action_just_pressed(“up”):
        animated_sprite.play(“Walk_Up”)
    elif Input.is_action_just_pressed(“down”):
        animated_sprite.play(“Walk_Down”)
    else:
        animated_sprite.play(“Idle”)

Edit: Just re-read your title and notice you said stop. You could change your else: to call stop() if that is more appropriate:

else:
    animated_sprite.stop()
1 Like

Thank ya I’ll try it!

Awesome It worked! also had to change it from .is_action_just_pressed to .is_action_pressed to make the original walk animation continue to play when the button was held. Thank ya!

1 Like