HuMMeR-SI
HuMMeR-SI

Reputation: 109

How do I check if a point is contained between 4 other points?

I have 4 points that creates some quadrilateral, I want to know if the fifth point is somewhere between them. something like these images:

enter image description here

enter image description here

It doesn't matter where the fifth Point is, I need to know if the fifth point is in the area that the other 4 points create.

also the 4 points are able to move. How do I do that?

Upvotes: 3

Views: 4254

Answers (3)

Jeffrey
Jeffrey

Reputation: 313

public class PolygonFence
{
    public List<Point> PointList = new List<Point>();

    public PolygonFence(List<Point> points)
    {
        foreach (Point p in points)
        {
            this.PointList.Add(p);
        }
    }

    public int Count()
    {
        return PointList.Count;
    }

    public bool IsWithinFence(Point p)
    {
        int sides = this.Count();
        int j = sides - 1;
        bool pointStatus = false;
        for (int i = 0; i < sides; i++)
        {
            if (PointList[i].Y < p.Y && PointList[j].Y >= p.Y || PointList[j].Y < p.Y && PointList[i].Y >= p.Y)
            {
                if (PointList[i].X + (p.Y - PointList[i].Y) / (PointList[j].Y - PointList[i].Y) * (PointList[j].X - PointList[i].X) < p.X)
                {
                    pointStatus = !pointStatus;
                }
            }
            j = i;
        }
        return pointStatus;
    }
}

Add the points in to PointList and call the IsWithinFence() method. Point p is the point that you want to check if it is inside the polygon or not. About the moving part, you must figure that out by yourself!

Upvotes: 0

Alaa Jabre
Alaa Jabre

Reputation: 1883

You can use GraphicsPath class.

Point p1 = new Point(1,0);
Point p2 = new Point(10, 3);
Point p3 = new Point(9, 13);
Point p4 = new Point(3,2);
Point p = new Point(5,5);
GraphicsPath g = new GraphicsPath();
g.AddPolygon(new Point[] { p1, p2, p3, p4 });
var result = g.IsVisible(p);

Upvotes: 5

Iwo Kucharski
Iwo Kucharski

Reputation: 3825

If you have coordinates of these points try to get linear equation of points which are creating quadrilateral. I'll explain it with point in triangle. Let's say we have 3 points outside:

A(-1,-1)
B(0,2)
C(1,1)

and one inside:

D(0,0)

You can find linear equation for outside points:

AB -> y = 3x + 2
BC -> y = -x + 2
CA -> y = x

Then you calculate y for x=0 (because point D have x=0) and you know that D is below AB, below BC but it in CA (if it were above CA it would be inside triangle ABC).

Upvotes: 1

Related Questions