ldg
ldg

Reputation: 451

Check if coordinates are within a rectangle

I am having a problem checking if coordinates are within a rectangle. I need to check if a specific object is within a certain range of coordinates. For example, given the rectangle below:

enter image description here

Having the coordinates highlighted in red and the coordinates of my blue object, I can check whether my objects is inside the rectangle, by doing (this is the simplest solution I can think of):

if xa > x1 and xd < x4 and ya > y1 and yb < y2:
    #success

Assuming my origin is in the top-left of the image, this is always true: xa = xb, xd = xc, ya = yd and yb = yc, this is pretty straightforward.

I am having problems when my rectangle rotates, like the image below:

enter image description here

I am always having all the coordinates, in red and in blue of my object. Which one will be the most efficient approach to use in this case?

I have used Python code, but this is more a logic question, I can't really find a solution.

Thank you in advance

Upvotes: 3

Views: 3394

Answers (1)

DavidPM
DavidPM

Reputation: 475

Although a bit late for an answer, notice that you can always find the straight line (i.e. hyperplane) between any two known points on the plane. In particular, you can define the straight lines to which all the segments of the outer rectangle belong (that is, the straight line that contains (x1,y1) and (x2, y2), the line that contains (x2, y2) and (x3,y3) and so on). Once you have the equation of any such line you can check whether a particular point lies 'above' such line, 'below' or inside it. By using the same logic you use for the simple case you can determine whether or not a particular point belongs to the rectangle (that is, if the point lies inside or below the straight line passing through the points (x1,y1) and (x4,y4), above or inside the line passing through the points (x2,y2) and (x3,y3) and so on).

Upvotes: 1

Related Questions