Unity3d判断一个点是否在多边形内
程序员文章站
2022-04-02 21:22:20
...
C#版本
public static bool ContainsPoint(Vector2[] polyPoints, Vector2 p)
{
var j = polyPoints.Length - 1;
var inside = false;
for (int i = 0; i < polyPoints.Length; j = i++)
{
var pi = polyPoints[i];
var pj = polyPoints[j];
if (((pi.y <= p.y && p.y < pj.y) || (pj.y <= p.y && p.y < pi.y)) &&
(p.x < (pj.x - pi.x) * (p.y - pi.y) / (pj.y - pi.y) + pi.x))
inside = !inside;
}
return inside;
}
JS版
static function ContainsPoint (polyPoints : Vector2[], p : Vector2) : boolean {
var j = polyPoints.Length-1;
var inside = false;
for (i = 0; i < polyPoints.Length; j = i++) {
if ( ((polyPoints[i].y <= p.y && p.y < polyPoints[j].y) || (polyPoints[j].y <= p.y && p.y < polyPoints[i].y)) &&
(p.x < (polyPoints[j].x - polyPoints[i].x) * (p.y - polyPoints[i].y) / (polyPoints[j].y - polyPoints[i].y) + polyPoints[i].x))
inside = !inside;
}
return inside;
}