Need help writing the code for a "second_idle" animation that starts a few seconds after the "first_idle" animation

Godot Version

4.2.2 stable

Question

Hello! I want to add a second idling animation to my character. I would like it to start a few seconds after the player idles.

I tried using the Timer node, to put “await get_tree().create_timer(5.0).timeout” between the two idle animations, using the _animation_finished() signal and other ideas but it always fails. It’s either the “second_idle” animation keeps repeating itself in accordance with the timer (something like that…) or the “second_idle” animation is cancelled right away.

I understand it must be because “process” runs every frame so it goes back to “first_idle” right away, but I can’t manage to fix it.

Thanks in advance!

My current character’s script (fresh of Brackeys’ tutorial…):

extends CharacterBody2D


const SPEED = 130.0
const JUMP_VELOCITY = -270.0

# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")

@onready var animated_sprite = $AnimatedSprite2D


func _physics_process(delta):
	# Add the gravity.
	if not is_on_floor():
		velocity.y += gravity * delta

	# Handle jump.
	if Input.is_action_just_pressed("jump") and is_on_floor():
		velocity.y = JUMP_VELOCITY

	# Get the input direction: -1, 0, 1
	var direction = Input.get_axis("move_left", "move_right")
	
	# Flip the Sprite
	if direction > 0:
		animated_sprite.flip_h = false
	elif direction < 0:
		animated_sprite.flip_h = true
		
	# Play animations
	if is_on_floor():
		if direction == 0:
			animated_sprite.play("first_idle")
			print("first_idle")
		else:
			animated_sprite.play("run")
			print("run")
	else:
		animated_sprite.play("jump")
		print("jump")
	
	if direction:
		velocity.x = direction * SPEED
	else:
		velocity.x = move_toward(velocity.x, 0, SPEED)

	move_and_slide()

I think I just have a pretty hard time with if the else and elif statements and signals…

Use animation tree

The only thing you have to do is ask which animation is playing when the timer ends:
If is playing the “Idle_1” animation then play “Idle_2” and viceversa and start de timer with same time (or another one each time with a random or samething similar…). I understand that these two animations have no end (Loop activated).

Another option is to use the AnimationTree Node as mentioned by the partner above…

I hope this is usefull for you

Thank you both.

KingGD: I will check the AnimationTree node. I don’t think I ever tried it before. Thanks! I will report later.

Ironsx: I will try again and paste the code and other information here, maybe you or someone else will be able to tell me what I am doing wrong. What you are saying is what I tried to do… well, what I wanted to do at least, but like I said it kept cancelling back to « first_idle » or the character was looping the first « first_idle » animation. Thank you!

1 Like