How to detect click on a RigidBody2D

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

Hello,
I am new to Godot (fluent in python) and I am trying to write my first game. It’s a simple physics puzzle game in which you click on some objects and they disappear/get destroyed. After making my research I understood that RigidBody2D was the way to go since it has built in physics. However I can not detect the input on my objects. Following a tutorial, I added a custom item in Input Map: ui_touch with left mouse button. I make the object pickable in the inspector then I connect the input_event of my object to itself and write the following code but nothing happens: (I’m using Godot 3.2.1)

extends RigidBody2D

func _on_test_1_input_event(viewport: Node, event: InputEvent, shape_idx: int) → void:
if event is InputEventMouseButton:
if event.is_pressed():
print(“Object clicked”)

Thank you in advance.
Note: The indentation is correct in my code

Your code works fine for me. Have you added a CollisionShape2D to your RigidBody2D? Make it visible during testing under Debug > Visible Collision Shapes to ensure it’s positioned correctly and your clicking inside the shape.

njamster | 2020-04-09 10:52

njmaster, thank you for your answer. Yes I have added a CollisionShape2D to my RigidBody2D. I followed your suggestion and made the collision shape visible. It is actually visible and I click inside of it. Still no luck.

korayozbay | 2020-04-09 11:23

Have you checked that the callback is connected correctly? Does it e.g. print a line on other events when your code looks like this:

func on_test1_input_event(viewport: Node, event: InputEvent, shapeidx: int) -> void:
    print("Any input event")
    if event is InputEventMouseButton:
        if event.is_pressed():
            print("Object clicked")

Maybe you can upload an example project with the problem?

njamster | 2020-04-09 12:01

Hello again njmaster. I followed your advice and nothing is being printed on the output. I would definitely try and upload the project. I just need to figure out how to do it.
Thank you again for your support and patience, I really appreciate it.

korayozbay | 2020-04-09 12:32

Hi,
I have uploaded the project to Google Drive. You can download it here Thank you so much for your support. For your info, the second file is much easier to explore. Just run the level_template.tscn and you will see my problem.

korayozbay | 2020-04-09 12:39

:bust_in_silhouette: Reply From: njamster

In your LevelTemplate-scene you have to select the TextureRect-node and set its mouse_filter-property in the inspector to MOUSE_FILTER_IGNORE. Otherwise it will consume the input event before it reaches your player-character.

Thank you soooo much! That worked like a charm, you are my hero.

korayozbay | 2020-04-09 14:41