How to tell what sort of body I've hit in Area.body_entered()

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By kitfox

I’ve created an Area shape on my player character that I want to use as my characters ‘grab’ area. There are going to be several different objects in my scene that my character should be able to grab. I’ve added a listener to Area.body_entered() to keep track of when things enter grabbable range. However, I don’t know what to do with the body:Node that is passed to my listener method.

I need to be able to determine what sort of object I’m touching. For example, if I have a door object and a chest object, both with different scripts attached to their root, how do I know if I’ve bumped into a door or a chest? Is there a way to check the object to see if it has the openDoor() method that I’ve added to script I’ve attached to my door object?

:bust_in_silhouette: Reply From: Magso

body is the reference to the intersecting body so you can use any of these depending on the game’s setup.

#check by name
if == "door":

#check by group
if body.is_in_group("door"):

#check by node type
if body is StaticBody:

It’s worth pointing out that checking by name will likely result in errors when running multiple instances of the same scene as their names need to be unique.

In that case, using a group will be better. Make sure you add your door-scene to the correct group and be vary of the fact that group names are case-sensitive!

Is there a way to check the object to see if it has the openDoor() method

Yes, there is.

njamster | 2020-03-27 11:37