How to tell if a line intersects a polygon in C#?

后端 未结 4 1845
悲&欢浪女
悲&欢浪女 2020-12-31 18:17

I have a question very similar to this:

How to know if a line intersects a plane in C#?

I am searching for a method (in C#) tha

4条回答
  •  感情败类
    2020-12-31 18:57

    Slightly off topic, but if the line is infinite I think there's a much simpler solution:

    The line does not go through the polygon if all the point lie on the same side of the line.

    With help from these two:

    • Using linq or otherwise, how do check if all list items have the same value and return it, or return an “otherValue” if they don’t?
    • Determine which side of a line a point lies

    I got this little gem:

      public class PointsAndLines
      {
        public static bool IsOutside(Point lineP1, Point lineP2, IEnumerable region)
        {
          if (region == null || !region.Any()) return true;
          var side = GetSide(lineP1, lineP2, region.First());
          return
            side == 0
            ? false
            : region.All(x => GetSide(lineP1, lineP2, x) == side);
        }
    
        public static int GetSide(Point lineP1, Point lineP2, Point queryP)
        {
          return Math.Sign((lineP2.X - lineP1.X) * (queryP.Y - lineP1.Y) - (lineP2.Y - lineP1.Y) * (queryP.X - lineP1.X));
        }
      }
    

提交回复
热议问题