Detect is a body is inside a specific area2d when I pressed a button

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

Hi everyone,

here a probably basic question.

I have a node2D named ‘door’ with an area2D and its related collision shape, the main player, and a button A (actually is a simple Button but I probably moved to the touch_screen_button). I want to perform an action, e.g. open the door changing a sprite, when the main player is inside the door’s area2D and I’m pressing the button A.

I’m trying using the function func _on_Area2D_body_entered(body): to detect when my main player entered inside the area2D checking the body. So far it works but I don’t know at this point how to detect when I’m pressing the button.

I’m also tried to connect the door’s script with the signal _on_ButtonA_button_down provided by the button starting from the detection of the pressure on the button A. Even in this case, this signal is correctly fired but now I don’t understand how to detect if the ‘body’ of the main player is inside the Areaa2D of the door.

I hope it’s clear enough, thanks for any kind of help.

:bust_in_silhouette: Reply From: Bernard Cloutier

You don’t want your player to trigger 2 different objects if they’re close when they press ‘A’, right? If not, the solution is only a bit different (array instead of just a var).

Easiest way to do this is adding a member var to your player:

# in your player controller script:
var _interactable_object

func _on_Area2D_body_entered(body):
    if body.has_method("interact"):
        _interactable_object = body

func _on_ButtonA_button_down():
    if _interactable_object:
         _interactable_object.interact()

func _on_Area2D_body_exited(body):
    if body.has_method("interact"):
        _interactable_object = null

Just be careful that you don’t add the “interact” method to other bodies not meant for interacting. The nice thing about the has_method approach though is that you don’t have to code all of the cases of interactable objects (door, chest, npc conversation, pickup, etc) in your player script, you just have to define an “interact” method on them.

Hey Bernard,

thanks for the answer. No, I just want to trigger one single object when I press button A.
I like the approach you suggested and it looks like it perfectly works for what I need.

Thanks

esarca | 2020-10-14 20:16

Hey! if the solution provided by Bernard is good for you, consider selecting it, so others can see it is the preferred solution.

p7f | 2020-10-15 00:26

Done, thanks.

esarca | 2020-10-15 06:00

1 Like