Saturday 19 January 2013

Simple Rectangle Collision Detection

We use collision detection all the time. Grabbing a cup of coffee, scratching our nose, sitting on a chair... even when walking our body detects the presence of other objects and surfaces outside of its own.
For computers it's a bit different. They can't detect anything unless we tell them how.

(Unrotated) rectangle collision is one of the simplest ones. If any point (P) isn't between the coordinates of both axis of the rectangle (R), then it's not colliding:

if ( Px >= R1x  AND  Px <= R2x  AND
     Py >= R1y  AND  Py <= R2y){

     // The point is inside the rectangle
}
else{
     // The point is outside the rectangle
}










With 2 rectangles (R1 and R2) we need to check, on both axis, if the coordinates of the edges of the 1st rectangle is between the coordinates of the 2nd:

if ( R1x2 > R2x1 AND R1x1 < R2x2 AND
     R1y2 > R2y1 AND R1y1 < R2y2 ){

     // The rectangles collided
}



0 comments:

Post a Comment

 

Break-a-Loop Copyright © 2013 | Template design by O Pregador | Powered by Blogger Templates