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
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).
6 Comments
ch4rl1e97
does it actually matter where the collision object is, or just that its a child of the 3DArea?
rcorre
@ch4rl1e97 an
Area is a CollisionObject. The Area itself will emit an input_event signal which you can handle.ch4rl1e97
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 usedrcorre
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.rcorre
Yes, the collision shape should be aligned so it matches (roughly) the mesh.
|
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")