January 22, 2019, 04:18:32 PM *
Welcome, Guest. Please login or register.

Login with username, password and session length
   Home   Blogs Help Search Tags Login Register  
Pages: [1]   Go Down
Author Topic: Collision Detection Explained  (Read 4336 times)
0 Members and 1 Guest are viewing this topic.
Richard Marks

Respect: 3425
Offline Offline

Posts: 1027


« on: January 22, 2009, 11:00:20 AM »

Collision Detection Explained

Okay I get far too many emails about how to do collision detection.
Hopefully this will help!

I'm sure you have seen code like this:
bool Intersect(const FLOATRECT &A,const FLOATRECT &B)
    return(A.x+A.width>B.x && A.x<B.x+B.width && A.y+A.height>B.y && A.y<B.y+B.height);

and then said what the **** is that?!

well let me make it a clearer.

bool Intersect(const FLOATRECT &objectA, const FLOATRECT &objectB)
const int LEFT_EDGE = 0;
const int TOP_EDGE = 1;
const int RIGHT_EDGE = 2;
const int BOTTOM_EDGE = 3;

float boxA =
objectA.x, // left edge
objectA.y, // top edge
objectA.x + objectA.width // right edge
objectA.y + objectA.height // bottom edge

float boxB =
objectB.x, // left edge
objectB.y, // top edge
objectB.x + objectB.width // right edge
objectB.y + objectB.height // bottom edge

if (boxA[RIGHT_EDGE] > boxB[LEFT_EDGE])
if (boxA[LEFT_EDGE] < boxB[RIGHT_EDGE])
if (boxA[BOTTOM_EDGE] > boxB[TOP_EDGE])
if (boxA[TOP_EDGE] < boxB[BOTTOM_EDGE])
return true;
return false;

isn't that clearer to understand?
Just know though that the second form is slower to execute. So use the first.

Here is another one; checking if a point is within a rectangle:
typedef struct RectT
int l, t, r, b;
} Rect; // left, top, right, bottom

bool PointIsWithinRect(int x, int y, const Rect& r)
return (x > r.l && x < r.r && y > r.t && y < r.b);

and I'll explain it this time without code...

  • get a piece of paper and a pencil.
  • draw a box.
  • put your pencil point down outside the box to the right of it,
  • move it slowly to the left... the pencil point is X, Y

When the pencil point moves inside the box, its X is both the the right of the left edge of the box, and to the left of the right edge of the box right? The same logic applies to the Y axis.

so in English, the code above does this:

if X is to the right of the left edge of the rect,
if X is not to the left of the right edge of the rect,
if Y is below the top edge of the rect,
if Y is above the bottom edge of the rect,
the point X, Y is in the rect!

That help?

Hope it does. let me know if it doesn't.
next time I'll cover collisions with circles. Cool

Tags: code  collision detection 
Pages: [1]   Go Up
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.21 | SMF © 2015, Simple Machines Valid XHTML 1.0! Valid CSS!