0

I'm almost done with my project and have 1 remaining problem that ive been trying to research for the past couple days. I have been able to rotate my images, flip them horizontally and even swap them out thanks to all your help. But my one remaining issue is since im using basically a rectangle collision detection scheme, how do i do collision detection once the images have been rotated? It seems the rectangle scheme doesn't work once they are rotated....Thanks so much guys!

Razr19
  • 1
  • 4

1 Answers1

1

The separating axis theorem (SAT) mentioned by @klenwell is a good tool for determining if 2 convex polygons are intersecting. I have to admit I couldn't get the code in that link to work for me, but here's an alternative link to an SAT script with examples: https://github.com/jriecken/sat-js/blob/master/SAT.js

I would add this for consideration...

The math involved in the separating axis theorm is fairly lengthy because of the need to cross-test all vectors.

You can make the process more efficient by pre-testing whether 2 specific rectangles can possibly be intersecting using simpler math pre-tests.

If those 2 rects can't possibly be intersecting, then don't bother doing the more expensive tests on them.

The pre-test:

If the distance between any 2 rect centers is more than the sum of their halfDiameters then those 2 rects can't possibly be intersecting...so don't do the more expensive math tests on those 2 rects.

if( Math.abs(rect1.centerX-rect2.centerX) > rect1.halfDiameter+rect2.halfDiameter ){

    // rect1 & rect2 can't be intersecting...don't bother testing further

}

if( Math.abs(rect1.centerY-rect2.centerY) > rect1.halfDiameter+rect2.halfDiameter ){

    // rect1 & rect2 can't be intersecting...don't bother testing further

}

Since any rectangle's halfDiameter does not change, you can compute it once for each rectangle and reuse that saved halfDiameter.

rect1.halfDiameter=Math.sqrt(rect1.width*rect1.width+rect1.height*rect1.height)/2;

rect2.halfDiameter=Math.sqrt(rect2.width*rect2.width+rect2.height*rect2.height)/2;

The rect.centerX and rect.centerY are the current center of the rotated rectangle.

markE
  • 102,905
  • 11
  • 164
  • 176