Imagine two squares sitting side by side, both level with the ground like so:

two squares side by side

A simple way to detect if one is hitting the other is to compare the location of each side. They are touching if all of the following are false:

  • The right square's left side is to the right of the left square's right side.
  • The right square's right side is to the left of the left square's left side.
  • The right square's bottom side is above the left square's top side.
  • The right square's top side is below the left square's bottom side.

If any of those are true, the squares are not touching. But consider a case like this, where one square is at a 45 degree angle:

enter image description here

Is there an equally simple way to determine if those squares are touching?

  • \$\begingroup\$ What language are you using? if the squares are images and you use canvas, you could make a simple-ish function detecting the pixel to pixel position. \$\endgroup\$ – justanotherhobbyist Mar 24 '12 at 17:35
  • 3
    \$\begingroup\$ You shouldn't do pixel collision detection. It's far too slow compared to more elegant algorithms like SAT. \$\endgroup\$ – kevintodisco Mar 24 '12 at 17:46
  • \$\begingroup\$ @hustlerinc I'm using C++. The squares will be bitmaps drawn using Direct2D. I don't know what you mean by "use canvas". \$\endgroup\$ – Rob Mar 24 '12 at 17:53
  • \$\begingroup\$ @ktodisco I'm storing the coordinates of each square so it's just an if statement with up to four comparisons between floats. That is slower than the SAT? \$\endgroup\$ – Rob Mar 24 '12 at 17:55
  • \$\begingroup\$ @Rob your extension assumes that one square is always axis-aligned. It will not work if both squares are rotated. \$\endgroup\$ – kevintodisco Mar 24 '12 at 18:00

What you're looking for is called the Separating Axis Theorem. A tutorial of it can be found here.

Essentially what you want to do, in the case of Object Oriented Bounding Boxes (rotated squares) is project the half-vectors of those squares, let's say 'up' and 'right,' onto the axes in the coordinate spaces of each square. You also project the vector between the square centers on these axes. If, for any axis, the sum of the lengths of the projected half vectors is greater than the length of projected distance between the two squares, then they are not colliding.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.