Trigger an animation with _on_body_entered

Godot Version

4.6

Question

Hi! I’m a complete begginer to GDScript so I’m not understanding how to link some nodes to others.

I have this killzone scene that has this function:

func _on_body_entered(body: Node2D) -> void:
	Engine.time_scale = 0.5
	body.play_animation("die")
	print("You died!")
	timer.start()

I want to play the “die” animation when my players enter this Area2D, but I can’t figure it out. The play_animation function in the player script looks like this:

@onready var animated_sprite:AnimatedSprite2D = $AnimatedSprite2D


func play_animation(anim: String) -> void:
	animated_sprite.play(anim)

I code so my first thought was to make the function public, but I suppose that’s not how it works here hehe.

How can I do this?

Thanks! :slight_smile:

Did you set up collision shapes, masks and layers correctly so that the area can detect your player?

Is this text being printed to the console?

This code is from the Brackey’s tutorial, right?

Anyway, I don’t see anything wrong with the code. Does the killzone detect the player at all? Are there any errors?

Also, gdscript doesn’t have private vs public, everything is public.

Yes! Everything inside that function works but the line I mentioned, so I think masks and layers are correct

Yes! It’s from that tutorial.

Everything else works so the killzone it’s definitely detecting the player. There’s no errors at all.

1 Like

If you haven’t changed the player script from the Brackey’s tutorial, the player script will change the animation to “idle” on the next frame.

	if is_on_floor():
		if direction == 0:
			animated_sprite.play("idle")

I suggest that you move the death-animation handling code to the player so it’s all in one place. I’m not really a fan of how that particular tutorial does it.

Oh I didn’t notice that! I’ll test it tomorrow :slight_smile:

Yeah coming from Java I don’t really like it either but it is my first tutorial on Godot and I was just 100% focused on the engine UI so I didn’t care much about the code.

As I said I can’t test it rn but there is something that caught my attention: if the function call is syntactically correct, why was I not getting the code suggestion as I was writing that line? Is that normal? Am I missing some addon?

I don’t know which function you are talking about, but the code suggestion will only appear if the editor knows what type you’re calling the function on. Godot doesn’t enforce strict variable typing, so it won’t always know what type a variable is.

1 Like

Hey! I just tried and it worked. Thanks!

The function I was talking about was play_animation. When I was trying to call it from killzone.gd it didn’t give me any suggestions while I was writing it, but I figured it out!