This topic is now archived and is closed to further replies.


2d collision detection...

Recommended Posts

knealeaj    122
I have put a simple function to detect collision between two rectangles below x and y are positions w is the width of the rectangles. For a line just consider it a rectangle of 1 pixel witdth. Hope this was helpful

int Collision_Test(int x1, int y1, int w1, int h1,
int x2, int y2, int w2, int h2)
// this function tests if the two rects overlap

// get the radi of each rect
int width1 = (w1>>1) - (w1>>3);
int height1 = (h1>>1) - (h1>>3);

int width2 = (w2>>1) - (w2>>3);
int height2 = (h2>>1) - (h2>>3);

// get the centre of each rectangle
int cx1 = x1 + width1;
int cy1 = y1 + height1;

int cx2 = x2 + width2;
int cy2 = y2 + height2;

// compute differences
int dx = abs(cx2 - cx1);
int dy = abs(cy2 - cy1);

// test if the rectangles overlap
if (dx < (width1+width2) && dy < (height1+height2))
// else no collision

} // end Collision_Test

Share this post

Link to post
Share on other sites
FreJa    154
Thanks... But check this picture:

And Here

if I try to collide with the green square, it won't work... it will only work when I get to right again...

[edited by - FreJa on March 17, 2003 1:24:42 PM]

Share this post

Link to post
Share on other sites