Search code examples
godotgdscript3d-modellingaabb

how to convert form AABB space (get_center method) to world environment in godot 4


I use get_AABB in godot 4 which is bounding box of mesh, I actually use get_center which is center of mesh. my question is get_center which is vector3 is in world environment space or mesh environment? how can I convert from mesh environment to world environment.

Thanks in advance


Solution

  • The get_aabb method form VisualInstance3D returns an AABB in its local space.

    To get it in global coordinates do this:

    visual_instance.global_transform * visual_instance.get_aabb()
    

    Be aware, of course, that an AABB can't represent rotation, so what this is doing is transforming the extreme points of the AABB, and giving you the smaller AABB that contains them. The center position will be correct, but there is no guarantee that it will preserve its size.

    Each class that extends VisualInstance3D provides its own implementation. In the case of a MeshInstance3D you get the bounding box of its mesh.

    Another caveat worth mentioning is that you get the AABB of the VisualInstance3D itself, disregarding children.


    Addendum

    The above is code for Godot 4. As you are aware, in Godot 3 there was a get_transformed_aabb method. However it was removed to avoid confusion on what it did, and because it is easy to reimplement, as it did the same thing as the code I posted above. See: https://github.com/godotengine/godot/pull/66940

    About getting the scale, you can find how the transform scales the object like this:

    visual_instance.global_transform.basis.get_scale() * visual_instance.get_aabb().size
    

    Here we are doing a component-wise multiplication (a.k.a direct product) of the two vectors (not to be confused with dot product or cross product).

    Here visual_instance.global_transform.basis.get_scale() gives you the scaling before rotation.


    You can, of course, use the size of AABB:

    (visual_instance.global_transform * visual_instance.get_aabb()).size
    

    But is not the same thing. As the latter is size of the AABB that contains the extreme points of the original AABB after transforming them (including rotation and scaling).