Godot body_entered only for a specific object in the scene

636 Views Asked by At

In my project, I have an Area2D. I want to perform some actions if a CharacterBody2D I created overlaps it.

I am thinking of using the body_entered signal to do this. I connected the signal, but how do I determine which character body triggered the signal? I have multiple character bodys in the scene and only one can trigger this action on overlap.

2

There are 2 best solutions below

0
On BEST ANSWER

Best way imo, is to use layers and masks.

If you have a specific element like a player give it it's own layer. Then in your case set the collision mask to the specific layer.

Your area will then only collide with elements on the specified layer. No code needed at all.

0
On

You can add an if statement to check what exactly it is, for example if the body you want to interact with is the Player (or whatever class name you gave it):

_on_body_entered(body: Node2D) -> void:
    if body is Player:
        // code

Edit: and if in your case all those character bodies happen to be using the same class but you dont want to interact with all of them, you can check for the node name, which is the displayed name in the scene tree and you can change it to whatever you want:

_on_body_entered(body: Node2D) -> void:
    if body.name == "NodeName1":
        // code
    if body.name == "NodeName2":
        // other code