Playing an animation as soon as a scene is instantiated

Godot Version

v4.2.1.stable.official [b09f793f5]

Question

I’m very new to game design in general, so I apologize if any of this is obvious.
I’m making a 2d platformer where I want the player to leave behind an animated sprite every time they jump. The idea is that, in addition to the player character’s jump animation, there’s an extra effect on the ground.
image
In this image, the black and red ball is the player, and the blue circles are the “jump effects”. This effect is a separate scene that is instantiated when the player jumps.

The issue is that I can’t seem to get the animation to play.
Here is the code for the jump effect:

func _enter_tree():
	$AnimatedSprite2D.play


func _on_animated_sprite_2d_animation_finished():
	queue_free()

I previously tried running the play function in _ready(), but that didn’t work either.

And here are the relevant parts of the player code:

func _ready():
	jump_effect = load("res://jump_effect.tscn")
	screen_size = get_viewport_rect().size
	hide()
	if Input.is_action_just_pressed("jump") and is_on_floor():
		var jump = jump_effect.instantiate()
		jump.position = global_position
		get_parent().add_child(jump)
		velocity.y = JUMP_VELOCITY

It is probably not playing just because when the scene is instantiated, the children nodes are not ready yet (ready process flows from root to children), so all you should need to do is make a function like

func play_start_animation():
	$AnimatedSprite2D.play()

and then call it deferred after you add it as a child

get_parent().add_child(jump)
jump.play_start_animation.call_deferred()

That works, though I also realized I forgot the parentheses on the play function.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.