Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Point in axis aligned rectangle test?

Tags:

c++

c

algorithm

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.

like image 850
jmasterx Avatar asked Dec 05 '25 20:12

jmasterx


1 Answers

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.

like image 99
Benjamin Lindley Avatar answered Dec 08 '25 11:12

Benjamin Lindley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!