Topic was automatically imported from the old Question2Answer platform.
Asked By
pr0face40
I created a 3D procedural world made of cubes with the use of the gridmap node and i want to select one of the cubes by clicking on it but i don’t know how can i select a cube and then detect the position of the selected cube. I hope someone can help me out. (Sorry if my english isn’t correct)
Then there are a few ways to find which cube you are pointing at.
The easiest is probably to give your cubes a collision body: in your gridmap scene, add a StaticBody with a CollisionShape having a BoxShape. Once you’ve done that, you can raycast from _physics_process to get which cube your mouse is hovering, and then convert the hit position into grid position using world_to_map.
See the doc about raycasting: Ray-casting — Godot Engine (3.1) documentation in English
Another way if you are adventurous, is to implement voxel raycasting. This is a bit harder and only works with cubes, but it can run without physics:
The idea is first to convert your ray into local gridmap coordinates (but you won’t need that if it’s in (0, 0, 0) with no scaling).
Then, you iterate forward by slighlty moving a point step by step along the direction of the ray, and check each time if the point in space corresponds to a cell of the grid (still using world_to_map). This can be a first easy implementation, but it’s imprecise and a bit slow. A better algorithm for this would be like this (I only made it C++ though, needs translation into GDScript): https://github.com/Zylann/godot_voxel/blob/12a97cca5aa2fbbd6ee6d5677479be5d6d624fbf/util/voxel_raycast.cpp