Game Development Reference
In-Depth Information
Given the importance of the rectangle class during user interface development we will see
the implementation of the useful operations we can perform on rectangles.
Point in Rectangle
If the rectangle is axis aligned, the test to determine if a point is within it is trivial, we need
to compare the point in question against the boundaries of the rectangle and verify that if
the point is within all of the rectangle's edges, then it cannot possibly be outside of it.
Which translates into the following code:
bool rectangle::Contains(float x, float y)
{
return (x >= Left() && x <= Right() && y >= Top() && y <= Bottom());
}
Less trivial cases arise when the rectangle in question is not axis aligned, one interesting
approach to this problem is to create four triangles, using two points in the rectangle and
the point in question. Then calculate the area of each triangle and sum them, if the total
area is greater than the area of the rectangle, we can conclude that the point lies outside of
the rectangle, if however, the area is precisely the area of the rectangle, then it is inside.
This method has the benefit that it's valid for any convex polygon, the downside is the
number of operations required to calculate the areas, and the fact that we need to test for
equality toknowifthe point isinside, means that care must betaken toensure that floating
point precision does not affect the result of our calculation.
Search WWH ::




Custom Search