How can I determine whether a 2D Point is within a Polygon?

前端 未结 30 2100
醉梦人生
醉梦人生 2020-11-21 05:06

I\'m trying to create a fast 2D point inside polygon algorithm, for use in hit-testing (e.g. Polygon.contains(p:Point)). Suggestions for effective tech

30条回答
  •  孤独总比滥情好
    2020-11-21 05:47

    Scala version of solution by nirg (assumes bounding rectangle pre-check is done separately):

    def inside(p: Point, polygon: Array[Point], bounds: Bounds): Boolean = {
    
      val length = polygon.length
    
      @tailrec
      def oddIntersections(i: Int, j: Int, tracker: Boolean): Boolean = {
        if (i == length)
          tracker
        else {
          val intersects = (polygon(i).y > p.y) != (polygon(j).y > p.y) && p.x < (polygon(j).x - polygon(i).x) * (p.y - polygon(i).y) / (polygon(j).y - polygon(i).y) + polygon(i).x
          oddIntersections(i + 1, i, if (intersects) !tracker else tracker)
        }
      }
    
      oddIntersections(0, length - 1, tracker = false)
    }
    

提交回复
热议问题