My question is, how do I compute the smallest possible box that entirely contains my collider, in local coordinates ? I could use the collider.bounds.size
value, but the problem is that this value is always aligned to the world coordinates. This means that, if my boat is rotated on Y by 45 degrees in world coordinate, this box is going to be much bigger than if the boat wasn’t rotated at all. I would like to find the size of the smallest bounding box having the same rotation as my collider. How can I do that ?
Here is more details about the context of my problem :
I’ve written a “drag” scripts that computes more realistic drag physics than the default Unity drag property, which isn’t good enough for boats. For that I have a “wall” of points that is constantly ahead of an object, regardless of the direction it is moving to. I.e if it goes forward, the wall is ahead of it and if it goes backward, the wall is behind it. That “wall” contains X * Y points from which I am casting rays in the opposite direction of the velocity. The ray casts hitting the object will apply a drag force on it, and those who don’t hit it will not apply any force.
I made that “wall” big enough so that it will always be at least as big as would be the projection of the object on the wall for any possible rotation. It’s side length is collider.bounds.size.magnitude
.
However, most of the time, only a small portion of the ray casts are going to hit the object. For example, if I have a narrow boat going forward, then there is probably only 10% - 20% of the ray casts going to hit the ship, so there are plenty of ray casts which I could avoid doing in order not to waste performance.
I would like to have some “begin X”, “end X”, “begin Y” and “end Y” values so that I only cast rays from a sub-rectangle of that wall that would be big enough. For that I would like to know the size of the “rotated” bounding box of my collider.
EDIT : I thought about doing this :
// Save the original object rotation to restore it later.
Quaternion rotationBackup = gameObject.transform.rotation;
// Set a 0, 0, 0 rotation to the object in order to reduce as much as possible the size of its AABB.
gameObject.transform.rotation = Quaternion.Euler(0f, 0f, 0f);
// Get the size of the smallestAABB.
Vector3 aabbSize = collider.bounds.size;
// Restore the original rotation.
gameObject.transform.rotation = rotationBackup;
But I’m not sure whether it will work because I don’t know if changing the rotation of the object will also update collider.bounds.size immediately or if that value is only updated later.
EDIT : See the comments below the accepted answer for more information.