4

I am trying my best to build a mobile game in the godot game engine. And i have run into a problem. In a 3D game, how can i detect a mouse click on a specific object or rather where that object is on the screen. I do not understand how to use the control nodes in order to to this.

2 Answers 2

5

The easiest way to make a 3D object clickable is to give it a CollisionObject (such as a StaticBody) and connect to the input_event signal. For example, to detect a left-click:

extends StaticBody

func _ready():
    connect("input_event", self, "on_input_event")

func on_input_event(camera, event, click_position, click_normal, shape_idx):
    var mouse_click = event as InputEventMouseButton
    if mouse_click and mouse_click.button_index == 1 and mouse_click.pressed:
        print("clicked")

The docs mention that touch events are similar to click events.

Note that input_ray_pickable must be true on the CollisionObject (this is the default).

Sign up to request clarification or add additional context in comments.

6 Comments

does it actually matter where the collision object is, or just that its a child of the 3DArea?
@ch4rl1e97 an Area is a CollisionObject. The Area itself will emit an input_event signal which you can handle.
I'd read elsewhere that this did not apply for 2D Areas and required a 2D collision box, I assumed the same applied to 3D, is this not the case? Edit: I've checked, you have to add a CollisionShape to the 3DArea, or the editor itself complains at you about it having no shape? I'll just stick it into its own scene with everything stuck in 0,0,0 and instance the scene when I need it, so positions don't matter, it'll all move as one when being used
Ah, I think we got a little mixed up over the CollisionObject/CollisionShape terminology. Any CollisionObject (Area, StaticBody, ect.) must have one or more CollisionShapes in order to detect any collisions.
Yes, the collision shape should be aligned so it matches (roughly) the mesh.
|
3

The rcorre's answer is right but just to give an update, in Godot4 that code looks like this:

func _ready():
    input_event.connect(on_input_event)

func on_input_event(camera, event, click_position, click_normal, shape_idx):
    var mouse_click = event as InputEventMouseButton
    if mouse_click and mouse_click.button_index == 1 and mouse_click.pressed:
        print("clicked")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.