BBloggsbott
BBloggsbott

Reputation: 388

Godot body_entered only for a specific object in the scene

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.

Upvotes: 0

Views: 2627

Answers (2)

Bugfish
Bugfish

Reputation: 1729

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.

Upvotes: 1

Davidhdm
Davidhdm

Reputation: 81

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

Upvotes: 2

Related Questions