I was wondering if the following algorithm to check if a point is inside a rectangle is valid. I've developed it using my own intuition (no strong trig/math basis to support it), so I'd love to hear from someone with more experience in the matter.
Context:
- The rectangle is defined with 4 points. It could be rotated.
- Coordinates are always positive.
- By definition, the point is considered inside the rectangle if intersects it.
Hypothesis:
- Use the distance between the point and the rectangle vertices (first diagram below).
- The maximum possible total distance is when the point is in one vertex (second diagram).
- If the point is just outside the rectangle, the distance will be greater (third diagram).
Diagram link: http://i45.tinypic.com/id6o35.png
Algorithm (Java):
static boolean pointInsideRectangle(Point[] rect, Point point) {
double maxDistance = distance(rect[0], rect[1]);
maxDistance += distance(rect[0], rect[2]);
maxDistance += distance(rect[0], rect[3]);
double distance = 0;
for (Point rectPoint : rect) {
distance += distance(rectPoint, point);
if (distance > maxDistance) return false;
}
return true;
}
Questions: is this correct?