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

前端 未结 30 2208
醉梦人生
醉梦人生 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:57

    Swift version of the answer by nirg:

    extension CGPoint {
        func isInsidePolygon(vertices: [CGPoint]) -> Bool {
            guard !vertices.isEmpty else { return false }
            var j = vertices.last!, c = false
            for i in vertices {
                let a = (i.y > y) != (j.y > y)
                let b = (x < (j.x - i.x) * (y - i.y) / (j.y - i.y) + i.x)
                if a && b { c = !c }
                j = i
            }
            return c
        }
    }
    

提交回复
热议问题