Testing What Scene a Body is in Godot
You’ve made a scene in Godot that you want to import into another scene. Let’s say it’s a balloon, and you want to include it in a scene with a bunch of other balloons. These balloons move around and you decide to add an Area2D to the scene that will pop every balloon that enters.
How do you detect whether the body entering the Area2D collision shape is a balloon? Well, you’ve got the collisions layers work out, but let’s say you want to go a little further.
It may seem like you can check the node name
, but that’s the name the node will have within the imported scene, i.e. the room in this example. One approach is checking whether the node has a non-empty scene_file_path
. If the node is from a pack scene, this would be set to the filename the imported scene is from:
func _on_area2d_body_entered(body):
if body.scene_file_path == "res://scenes/balloon.tscn":
body.pop_balloon()
This works, but we can do better here.
The other is by setting the class name of the scene. GDScript classes are anonymous by default, which is usually fine, but it is possible to name a class, using the class_name
keyword. This has some potentially useful things, such as making the class choosable as a node type within the scene editor (albeit without the actual scene nodes, making it more likely to be more useful as a specialised form of node type), but for our purposes, it allows you to check to see what type of body has entered the Area2D.
To use here, set the class_name
to the script attached to the balloon scene:
class_name Balloon
extends CharacterBody2D
# balloon things go here, etc.
Then, in your on_body_entered
signal handler, use the is
keyword to test whether the body is a balloon:
func _on_area2d_body_entered(body):
if body is Balloon:
body.pop_balloon()
Sources: