2

Let's say computer randomly generate 4 points on canvas. points are

A[x1,y1]
B[x2,y2]
C[x3,y3]
D[x4,y4]

I need to decide if a point P [x,y] is insided the area built by the 4 points. the 4 sides are AB, BC, CD, and DA.

I can compare the areas if all inside angles are less than 180:

if Area(APB + BPC + CPD + CPA) = Area(ABCD)
then P is inside the quadrangle. 
Example: Area of ABC = 1/2 |(A*(By−Cy)+B*(Cy−Ay)+C*(Ay−By))|

But the method of comparing area may not work for the situation if one of the angle inside the quadrangle is bigger than 180.

How to deal with this situation ?

Di Wang
  • 511

1 Answers1

2

Make sure your points are arranged clockwise. Set them up like so.

$\begin {bmatrix} x_1 & y_1\\x_2&y_2\\x_3&y_3\\x_4&y_4 \end{bmatrix}$

By the shoelace algorithm the area of the quadrilateral $A= x_1 y_2 + x_2 y_3 + x_3 y_4 + x_4 y_1 - y_1 x_2 - y_2 x_3 - y_3x_4 - y_4 x_1$

What are we doing... we multiply down and to the right (looping around at the bottom to the top) and add up the products. And then we multiply up and to the right and add up the products. Do you see why this is described as shoelaces?

If they are counterclockwise then you will get the negative of the area. And if you are "twisted up," i.e. $(x_1,y_1)$ is diagonal from $(x_2,y_2)$ then you have nothing relevant.

Let's call the new point $(x_a,y_a)$

Now shoelace through 5 points.

$\begin {bmatrix} x_1 & y_1\\x_2&y_2\\x_3&y_3\\x_4&y_4\\x_a&y_a\end{bmatrix}$

If the area the 5-gon is greater, then the added point is outside the 5-gon. if the area of the 5-gon is less than your quadrilateral, you are not done quite yet. If this is a programming task, program it to swap $(x_a,y_a)$ through the different rows of the matrix. i.e.

$\begin {bmatrix} x_1 & y_1\\x_2&y_2\\x_3&y_3\\x_a&y_a\\x_4&y_4\end{bmatrix}, \begin {bmatrix} x_1 & y_1\\x_2&y_2\\x_a&y_a\\x_3&y_3\\x_4&y_4\end{bmatrix}, \begin {bmatrix} x_1 & y_1\\x_a&y_a\\x_2&y_2\\x_3&y_3\\x_4&y_4\end{bmatrix}$

And if the area no matter how you position $(x_a, y_a),$ the area is less than the area of the quadrilateral, then $(x_a,y_a)$ is inside the figure.

Doug M
  • 57,877