Henehefu 用 ウィキ

メニュー



- Views

最近の更新

取得中です。

Csharp > TriangleContains > cs


※上記の広告は60日以上更新のないWIKIに表示されています。更新することで広告が下部へ移動します。

public class Point
    {
        public Point(double x, double y)
        {
            this.X = x;
            this.Y = y;
        }
 
        public double X
        {
            get;
            set;
        }
 
        public double Y
        {
            get;
            set;
        }
    }
 
    public class Line
    {
        public Line(Point a, Point b)
        {
            this.A = a;
            this.B = b;
        }
 
        public Point A
        {
            get;
            set;
        }
 
        public Point B
        {
            get;
            set;
        }
 
        public int GetSide(Point p)
        {
            Func<Point, Point, Point, double> f = (x, y1, y2) => x.X * (y1.Y - y2.Y);
            var n = f(p, A, B) + f(A, B, p) + f(B, p, A);
            return Math.Sign(n);
        }
    }
 
    public class Triangle
    {
        public Triangle(Point a, Point b, Point c)
        {
            this.A = a;
            this.B = b;
            this.C = c;
        }
 
        public Point A
        {
            get;
            set;
        }
 
        public Point B
        {
            get;
            set;
        }
 
        public Point C
        {
            get;
            set;
        }
 
        public bool Contains(Point p)
        {
            var ab = new Line(A, B);
            var bc = new Line(B, C);
            var ca = new Line(C, A);
            var pab = ab.GetSide(p);
            var pbc = bc.GetSide(p);
            var pca = ca.GetSide(p);
            var sides = new[] { pab, pbc, pca };
            var conds = new Func<int, bool>[]{
                s => (0 < s),
                s => (0 > s),
                s => (0 <= s),
                s => (0 >= s),
            };
            return conds.Any(cond => sides.All(cond));
        }
    }
 
    static class TriangleTest
    {
        void Test()
        {
            var triangle = new Triangle(new Point(0,0), new Point(100, 0), new Point(100, 100));
            var point = new Point(50, 50);
            var result = triangle.Contains(point);
            Console.WriteLine(result);
        }
    }
 

タグ一覧