My rectangle structure has these members: x, y, width, height.
Given a point x, y what would be the fastest way of knowing if x, y is inside of the rectangle? I will be doing lots of these so speed is important.
My rectangle structure has these members: x, y, width, height.
Given a point x, y what would be the fastest way of knowing if x, y is inside of the rectangle? I will be doing lots of these so speed is important.
if (p.x > x && p.y > y && p.x < x+width && p.y < y+height)
This should only be a handful of assembly instructions.
It assumes that x, y of the rectangle are always the smallest value coordinates of the rectangle. It also discounts points that are on the border of the rectangle.
In C++ (can be trivially translated to C):
bool pointInRectangle( Point const & p, Rectangle const & r ) {
return
((r.x <= p.x) && (p.x <= (r.x + r.width ))) &&
((r.y <= p.y) && (p.y <= (r.y + r.height)));
}
This is how I usually do it. Given a point that is outside of the rectangle, this will do fewer tests in 3 out of 4 cases. And sometimes only one test is done.
if(point.x < rect.x) return false;
if(point.y < rect.y) return false;
if(point.x >= rect.x + rect.width) return false;
if(point.y >= rect.y + rect.height) return false;
return true;
Which one you use should be dependent upon whether you anticipate more collisions or more misses.
If you're targetting a specific CPU, e.g. x86, the you can use SIMD (i.e. SSE) to do a very fast branchless test. The trick is to use 4 x 32 bit ints to represent the rectangle, which maps to a SIMD vector (it needs to be 16 bytes in size and 16 byte aligned).