How do I detect if I am clicking on a meshinstance3d?

Godot Version

4.2.2 (or 4.2.1)

Question

Hi

Is there a way to check if my mouse is inside of a meshinstance3d (of an instanced scene) either when click or hovered over it?

I can get the transformed boundingbox but I am not able to figure out if my mouse pointer is in a mesh instance or not.

thanks

Use a StaticBody3D under your MeshInstance3D and also have a CollisionShape3D under the static body:
image

Then look at the signals for the static body. You will see mouse_entered and mouse_exited.

That’s one way. Another is to use a ray.

hth

2 Likes

Thanks, I am trying to do this in the script in runtime without adding objects because this is going to be procedural so i cant constantly add collisions shapes or signals in the editor.

I am interested in the Ray solution. Do you mind expanding on it?

I already have this , but I cant find if cursor3d is in a bbox of a mesh instance or not. I think the ray against this plane is doing a disservice to me, and I need to do this against the actual mesh instances and I do not know how to do it.

var cursorPlane = Plane(Vector3(0,1,0),-10.0)
cursor3D = cursorPlane.intersects_ray(camera3D.project_ray_origin(get_viewport().get_mouse_position()),
                                                camera3D.project_ray_normal(get_viewport().get_mouse_position()) 

You can also make the static body and the collision when you make the mesh. Rays also require the collision shape to detect any hits.

Another approach is more low-level. Start here:

You’d make an AABB “around” your cursor and then use RenderingServer class to find intersection. The problem is that your cursor is not actually in the screen, so I’m not sure how you’ll handle z depth.

1 Like

Thanks, do you think this method performant enough to be used in a 3d game and triggered either by a click or run in some kind of process?

Do be sure to choose the right class. If you are writing a tool (in-editor) you use different class to a game (that runs). I link to both in my post.

The underlying system if what all collision uses in Godot, so the ‘Server’ classes are the fastest you can get short of doing it all yourself in C++.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.