How can I get an OverlapBox with the exact same size and position as a BoxCollider?

I have a box collider on an object with a parent where I can adjust the size and centre along with the rotation and position on the transform of the object the collider is attached to using a script, plus the position of the transform on the parent object, in order to get the box just the right size and position in the world.


I want to get the exact same resulting position and size box but with Physics.OverlapBox. Normally I’d mess about with trial and error but the suggested Gizmos.DrawWireCube only allows for position and scale so I’m struggling to visualise the results.


So OverlapBox allows me to adjust the centre, halfExtents and orientation.


HalfExtents seems self explanatory, just half the size. And I guess I can just copy rotation into orientation? looks like the same thing? But maybe not? Will it need adjusting to account for the change in centre on the box collider?


Centre however is less obvious. With box collider I use both it’s centre and the objects transform position. I assume OverlapBox won’t be using the transform of the object the script is attached to? So I’ll have to adjust centre to be the result of the collider centre combined with that transform. Is there a simple way to do that?


I’m thinking there will be adjustments based on local space to world space. Like the OverlapBox centre is the world position, so I’ll need to find out what position the collider.centre is when converted back to world space? Would it be like the child of a child? as the centre seems local to a transform which itself has parent.


But I want to know if I’m even barking up the right tree before I start trying to get my head around that. Thanks in advance for any pointers.

You can visualize the box by setting Gizmos.matrix to collider.transform.localToWorldMatrix, then just drawing collider’s localspace box. After you set the matrix to localToWorldMatrix, you can just draw with center being the local collider’s center property and extents (as you described).

For the OverlapBox, you can do pretty much the same, you just have to calculate the center yourself. So, for example (untested)

Vector3 worldCenter = collider.transform.TransformPoint(collider.center);
Vector3 worldHalfExtents = collider.transform.TransformVector(collider.size * 0.5f); // only necessary when collider is scaled by non-uniform transform
Physics.OverlapBox(worldCenter, worldHalfExtents, collider.transform.rotation);

Accepted solution has a bug that BoxCollider’s rotation affects worldHalfExtents.
Here is a fixed code:

Vector3 worldCenter = box.transform.TransformPoint(box.center);
Vector3 worldHalfExtents = Vector3.Scale(box.size, box.transform.lossyScale) * 0.5f;
Physics.OverlapBox(worldCenter, worldHalfExtents, box.transform.rotation);