• ### What is your GameDev Story?

#### Archived

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

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

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

## Recommended Posts

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

##### Share on other sites
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

##### Share on other sites
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

##### Share on other sites
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

----------
Disco Love For Everyone

##### Share on other sites
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

##### Share on other sites
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

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 28
• 16
• 10
• 10
• 11
• ### Forum Statistics

• Total Topics
634111
• Total Posts
3015560
×