• Advertisement

Archived

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

2d collision detection...

This topic is 5452 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, How do I detect the collision beteween a square and a line in 2D? Thanks

Share this post


Link to post
Share on other sites
Advertisement
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))
return(1);
else
// else no collision
return(0);

} // end Collision_Test

Share this post


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

Here
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

  • Advertisement