Unproject_position but as a rectangle instead

Godot Version

4.6

Question

Please see https://www.youtube.com/watch?v=hSJ9nQWkucU at 1:25. When the character is in front of the crosshair, a 2D rectangle for “this object is being looked at” is created on the HUD.

How to do this in Godot?

While there is unproject_position (Camera3D — Godot Engine (stable) documentation in English) , I could only give it a Vector3 to get a Vector2 out of it, but then, how can I get the Vector3s that are farthest top-left to farthest bottom-right for a particular CollisionShape3D in Area3D / CharacterBody3D? Or must I do this some other ways?

If I could get x,y,w,h somehow, then this should be good to go.

(Un)project all 8 corners of the bounding box onto the camera/screen plane and then find their bounding rectangle.

@normalized sorry, that’s the part I do not know how to do. :sweat_smile: Would you mind provide me some links or keywords to lookup?

Presuming you want to do this for a mesh:

  • get mesh instance’s bounding box via get_aabb() It’ll return an AABB object.
  • position and end properties of that object define 2 opposite corners. By taking all 8 permutations of those two point coordinates you’ll get all 8 bounding box corners.
  • Transform all of those points to global space by multiplying them with mesh instance’s global_transform
  • Project them to viewport space using camera’s unproject_position
  • You’ll end up with 8 2d points. Find minimal and maximal x and y coordinate of those points which will give you the 2d bounding rectangle.
  • Draw the rectangle
2 Likes