🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

How do I test if a point is inside or outside a box?

Started by
4 comments, last by Benbe 24 years ago
Hi! I''m trying to make a two dimensional collision detection system. How do I test to see if a point is inside or outside a rectangle. Thank you for your help /Fredrik
Advertisement
Okay, say you have a rectangle defined as the following:

typedef struct Rect
{
int top;
int left;
int bottom;
int right;
} Rect;

you would do something like this

bool PtInRect( int x, int y, Rect myRect );
{
// Test against the x-axis
if ( ( x >= myRect.left ) && ( x <= myRect.right ) )
{
// We''ve passed the first test, so now check the y-axis
// Note: this is for a window coordinate system where (0,0) is in the top-left corner, OpenGL has (0,0) in the bottom-left corner, so you need to switch the y-axis test upside down
if ( ( y >= top ) && ( y <= bottom ) )
return true;
}
else
return false;
}

It''s that simple.

Morgan
Thank you!

But is was thinking of a test system where the rectangle can be rotated around its z-axis....so that the lines defining it aren''t constant''s but lines defined, for example, like y-2x=3, y-2x=6, 2y+x=3, and 2y+x=6.....is this possible to do easily. Or do I have to rotate everything else but the rectangle when I test collisions.

Thank you

Fredrik
If you want to check a rotated box, then you will
need to interpolate along each edge.

Look around for polygon collision detection (it gives me
a big massive headache so I can''t help you with code)


----------
Disco Love For Everyone
----------"i think that all this talking and such is paining my head to astounding annoyance" - Erick"Quoting people in your tag is cool. Quoting yourself is even cooler" - SpazBoy_the_MiteyDisco Love For Everyone
What you can always do is rotate the box and point back to a position where the box is not rotated anymore and then test. Of course this is done mathematically, so you would calculate the center of the box:

pos.x = (myRect.right - myRect.left)/2 + myRect.left;
pos.y = (myRect.bottom - myRect.top)/2 + myRect.top;

then rotate your point that you are collision detecting against the box back the number of degrees that the box is rotated, then use something like the PtInRect() function I previously used as an example. I''d give you the trig, or some better code, but I''m about to walk out the door. Hope this helps (it''s easier than interpolating along the lines).

Morgan
Thank you guys!

I''ll mess around with it for awhile. I''m thinking that Morgans idea might be the easiest for the moment. But perhaps I''ll have time to try both.

Thanks!

/Fredrik

This topic is closed to new replies.

Advertisement