Detect rotated cube or rectangle overlap instantly without using OnCollisionEnter

Sorry if this should be obvious, but I’ve looked through the documentation/forum posts quite a bit and there doesn’t seem to be an easy way to do this.

I’m looking for some function like

bool IsOverlapping(BoxCollider a, BoxCollider b)

Ideally this magic function will deal with cubes/colliders that are rotated and not axis aligned.

Yes, I know I can determine this by setting up OnCollisionEnter functions, but that happens to be really inconvenient, as ultimately, I’d be wanting to do something like this in a loop…

// psuedocode
BoxCollider a;
BoxCollider b;

for (int i = 0; i < 30; i++)
{
    // move collider a to the next position
    a.transform.position = new Vector3(i*10.0f, 0.0f, 0.0f);

    if (IsOverlapping(a, b))
    {
        // do something here.
    }
}

Bounds is an all encompassing bounding box that doesn’t rotate, right? So if you rotate your cube 45 degrees, the bounding box will actually be a bigger volume than the cube, because it’s made big enough to encompass the entire rotated cube. Or am I wrong in my understanding here?

I specifically want to check if 2 rotated cubes are touching.

1 Like

One way may be to get the position of each corner of the cube (the vertex there). Then for each vertex in cube a, see if that corner point falls in any side of cube b.
And then vice verce, see if any corner point in cube b falls in any side of cube a.
Hmm…well actually, that would only work in 2d. :slight_smile: sorry!

Can you just test for poly intersection of the faces?

I ended up figuring this out on my own because I couldn’t find a good solution and performance of oncollisionenter sucks.

For anyone curious about this, the simplest way to do it, without getting into scary intersection test math, is just to use the collider.raycast method to check all the edges of each box and see if either crosses into the other.

So you get each corner of both of your boxes. Then, you take all of the edges in A, and test them as rays against collider B. Then flip around and do the same for B and A. If any of those ray tests returns true, the colliders overlap. If not, they don’t. It’s 24 ray checks per object pair, which is probably slower than the optimal intersection math, but faster than oncollisionenter in a large world.

Hey! A long time has passed since my original post.
Last year I revisited the problem and I realized that there is now an easy solution to solve this -

Of course it checks against all colliders, but if you can use layer masks to narrow it down quite a bit.