I'm trying to make a character be removed from the scene after playing an animation. Do you have any ideas how this can be done? After the player enters the ‘DeathDetector’ (Area 2D), the animation plays indefinitely.
extends CharacterBody2D
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
var alive = true
var chase = false
var speed = 100
@onready var anim = $AnimatedSprite2D
func _physics_process(delta):
if not is_on_floor():
velocity.y += gravity * delta
var player = $"../../Player"
var direction = (player.position - self.position).normalized()
if alive == true:
if chase == true:
velocity.x = direction.x * speed
anim.play("run")
else:
velocity.x = 0
anim.play("idle")
if direction.x < 0:
anim.flip_h = true
else:
anim.flip_h = false
move_and_slide()
func _on_knight_detector_body_entered(body):
if body.name == "Player":
chase = true
func _on_knight_detector_body_exited(body):
if body.name == "Player":
chase = false
func _on_death_detector_body_entered(body):
if body.name == "Player":
body.velocity.y -= 50
death()
func death ():
alive = false
anim.play("death")
await anim.animation_finished
queue_free()
The animation_finished
signal will never be emitted if the "death"
animation is loopable; this prevents queue_free()
from executing.
To fix this, select your AnimatedSprite2D node, open the SpriteFrames panel at the bottom, choose the "death"
animation, and toggle off its loop property.