Checking if a point is inside a rectangle

Mar 17, 2013 at 5:52pm
How do you check if a point is inside a rectangle?

my upper left corner is _corner(10,10)
and my width is 10 , and height : 20;


This is my contains method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
bool Rect::Contains( Point p )
{
	if( p.GetX() >= _corner.GetX() + _width && p.GetY() >= _corner.GetY() + _height )
	{

                cout<<" it was not inside the rectangle"<<endl;
		return false;
	}
	else

	return true;


}


Is this the correct way to do it ? I'm pretty sure its not .
Mar 17, 2013 at 6:10pm
Well, I'd imagine the way to do it is to check if the first (x) coordinate is greater than or equal to 10 and less than or equal to 10 plus the width, AND that the height is greater than or equal to 10 and less than or equal to 10 plus the height. In your case, you have the less than or equal to part down, but you forgot to make the case when the point is, say, (1,1) or (17,2). You need another if statement to make sure both coordinates are greater than or equal to 10.
Mar 17, 2013 at 6:11pm
You need two tests for x and two tests for y.
For example
( p.GetX() >= _corner.GetX() ) && ( p.GetX() <= _corner.GetX() + _width )
Last edited on Mar 17, 2013 at 6:51pm
Mar 17, 2013 at 6:26pm
So I just need to add what you suggested Chervil.
Mar 17, 2013 at 6:51pm
The code I suggested is just for the x-values. You need another similar piece of code for the y-values.
Mar 17, 2013 at 6:53pm
Ok thanks !!
Topic archived. No new replies allowed.