Physics.OverlapBox() doesn't work right when rotation isn't zero

I’m having a problem that related to Physics.OverlapBox().

Let’s say that a given object is a cube and it has 2 colliders which are not intersecting each other. I am creating OverlapBoxes that have these colliders’ center and extent values. When the colliders (and OverlapBox) have zero rotation, it works (it finds both colliders), but when the colliders (and OverlapBox) have some rotation, OverlapBox finds 4 colliders.

First OverlapBox is finding the object’s first and second colliders and a second OverlapBox is collecting same colliders too. I think there is a problem when Physics.OverlapBox() has some rotation. But i could not find a solution.

Can you post the code you are using so we can see if it happens on our end? Also, what unity version are you using?
Are you saying that a single object has 2 collider components on it, and when there is no rotation, the overlapbox works fine, but when either the object or the overlapbox has a rotation, it for some reason detects 4 colliders when there are only 2 in the whole scene?

I had a similar problem, but as it turns our I was passing collider.bounds.size instead of collider.size to Physics.OverlapBox, and that increases in size when it’s not Axis Aligned, which led to it finding more overlaps then I was expecting when it was rotated. I believe the op was probably making a similar mistake (yes, I do know I’m necro’ing this, but in case someone ends up here from googling it like I did, this reply might help)

7 Likes

thx… after hours of struggling was that the hint that helped me

if anyone else has this problem. what i did was

Bounds bounds = object.GetComponent<MeshRenderer>().bounds;
Collider[] overlappings = Physics.OverlapBox(bounds.center, bounds.extents, object.transform.rotation);

though as it turns out, taking the bounds of an objects mesh renderer already includes the rotation.
so the correct code would be

Bounds bounds = object.GetComponent<MeshRenderer>().bounds;
Collider[] overlappings = Physics.OverlapBox(bounds.center, bounds.extents);
1 Like

Ignoring the necro, that’s the definition of what bounds are. They are an AABB. Taking the Bounds of anything is an AABB.

I don’t understand how your code improves anything as it still only works on a non-rotated box because only then are the AABB bounds equal to a box because then it’s axis-aligned.

The answer above is correct, yours isn’t I’m afraid to say.

1 Like