NOGDUS

Articles, Tutorials, and other things. => General Game Programming => : Richard Marks January 22, 2009, 11:00:20 AM



: Collision Detection Explained
: Richard Marks 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,
and
if X is not to the left of the right edge of the rect,
and
if Y is below the top edge of the rect,
and
if Y is above the bottom edge of the rect,
then
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. 8)


Sorry, the copyright must be in the template.
Please notify this forum's administrator that this site is missing the copyright message for SMF so they can rectify the situation. Display of copyright is a legal requirement. For more information on this please visit the Simple Machines website.