DirectX 2D Pixel collision detection,
Crossbones+ - Reputation: 3538
Posted 29 October 2009 - 12:06 PM
GDNet+ - Reputation: 13820
Posted 29 October 2009 - 01:24 PM
I'd start first by doing a simple bounding circle collision test between objects, because its easy to do an doesn't need the angle information, so its fast. The radius from the center of each box to its corner is sqrt((w/2)^2 * (h/2)^2), and we re-use the same calculation to find the distance between the center of the boxes sqrt((b2.x - b1.x)^2 * (b2.y - b1.y)^2). If the distance between the two box centers is greater than the sum of the two box radiai, then there is no possible collision. The news gets better though, since the you can cancel out the sqrt operation on each side of the equation to save yourself a lot of cycles.
You could also do something like the separating axis theorum (SAT) as another broad-phase test. It will get you a little bit more accurate results -- box to box, instead of bounding circle to bounding circle. It's probably worthwhile since much of the setup work it needs can be re-used by the final pixel-perfect test. I'll let google explain how it works for you, but you can choose to do both the SAT and bounding circle tests, or just one or the other, depending on what gives the best performance in your situation.
The big picture of the pixel-perfect test is that you want to select one of the boxes as your new basis based on its location and orientation, and then transform the other box into this basis (which box you choose as this new basis is arbitrary, so just pick either one -- although if either one happens to be axis-aligned (no rotation) it'll save you some work) -- this is the work that the SAT test requires (or at least can, the point is that you can structure this to share the work :) ). Finally you test whether the final location of the transformed mask's collidable pixels overlap any of the collidable pixels in the basis mask.
You can further optimize by divide & conqour if the collision masks are closed (no holes, and in one single piece) and convex, and depending on how 'pixel-perfect' you insist on being (or what it means for the realities of your game) you can sometimes fudge the collision masks a little such that divide and conqour can be applied.