I have some point of interests in 3D that I would like to show on HUD. For example, suppose we have the next destination that the player suppose to go, the HUD will have an icon for it. Here is an example, from 0:30 onward of this video: https://youtu.be/VQqGV1sc6pc . See the “next destination” icon that rotates around pointing the direction? Something like that.
So how to convert 3D coordinates of an object to 2D coordinates for 2D HUD?
Try this: get_viewport().get_camera_3d().unproject_position(global_transform.origin)
Or use the known 3D coordinates instead of global_transform.origin.
When using this (unproject_position) to position GUI elements over a 3D viewport, use is_position_behind to prevent them from appearing if the 3D point is behind the camera:
So the code above will make it so that if your 3D position of interest is not in the viewport, the 2D coordinates will still be within the window… only if the 3D position of interest is not behind the camera…
The issue is unproject_position will return the 2D coordinate invalidly if the 3D position is behind the camera. This means extra mathematics is required, but how to calculate for that?