I’ve discovered that Unity has a lot of faults/lacks for a commercial engine at version 3.5 (In this post I will only comment this concrete problem).
One of the most disapponting ones is the improper results of the function Rigidbody.ClosestPointOnBounds()
.
First, the proofs:
1.- Create a cube at (0,0,0) with rotation=(0,0,0), scale=(1,1,1) and attach a rigidbody component
2.- Create a empty game object (name it “son”) and make it son of the cube. Assign it the local position (1.5, 0, 0)
At this point the distance between “cube” and “son” is exactly 1.
5.- Add this script to “cube”
function Awake()
{
var go : GameObject = GameObject.Find("son");
if (go == null) print ("error !!!");
var pos : GameObject = new GameObject ("pos");
pos.transform.position = transform.rigidbody.ClosestPointOnBounds (go.transform.position);
}
6.- When running, it spaws a new (and empty) GameObject (“pos”) in correct the position: At (0.5, 0, 0) as it should do.
7.- From the editor, go to “cube” and rotate it about Y axis 45 degrees. Now “son” is at the correct position but “pos” IS NOT.
The reason is that a commercial engine at version 3.5 doesn’t supports OBB (Oriented Bounding Boxes), only AABB (Axis Aligned …).
After crawling the forums/answers I found this is a well known, old and never solved problem of Unity since at least March of 2009 (http://forum.unity3d.com/threads/29321-question-about-boxcollider(axis-aligned-gt-oriented-alig).
The developers claim that it’s difficult to find and algorythm to work with OBB, but even FREEWARE engines as Ogre3D implement it.
There is a fast and easy (although cheesy) solution wich dont needs any complex OBB algorythm:
Every object with a collider attached could automatically generate the 8 vertices of the OBB implemented as empty GameObjects being sons of the object with the collider attached and excluded from hierarchy window to make them invisible for the user.
- The calculation of the local position of these vertices is trivial because they are orthogonal to local (0,0,0).
- When the object is rotated/translated the vertices are shifted correctly because they are sons of the rotated/translated object.
- The position in the world of the vertices is also trivial: verticeName.transform.position
- The construction of the OBB having its 8 vertices is also trivial.
This would result in a minor RAM sacrifice (only the objects with collider/rigidbody attached would need them), and would allow to have OBBs:
- Better collision detection
- Know the dimensions of a object in runtime and consequently easy calculation of OBBs for complex objects
- Functions as ClosestPointOnBounds() would work properly
and many other problems derived from lacking of OBBs would be solved.
So, as Sheldon Cooper’s mother would say:
“Put down that Pepsi can full of bourbon that ain’t foolin’ no one, and start coding.”