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

前端 未结 30 2835
醉梦人生
醉梦人生 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 06:11

    Really like the solution posted by Nirg and edited by bobobobo. I just made it javascript friendly and a little more legible for my use:

    function insidePoly(poly, pointx, pointy) {
        var i, j;
        var inside = false;
        for (i = 0, j = poly.length - 1; i < poly.length; j = i++) {
            if(((poly[i].y > pointy) != (poly[j].y > pointy)) && (pointx < (poly[j].x-poly[i].x) * (pointy-poly[i].y) / (poly[j].y-poly[i].y) + poly[i].x) ) inside = !inside;
        }
        return inside;
    }
    

提交回复
热议问题