如何在c#中检查一个二维点是否在多边形内?
本文关键字:二维 是否 多边形 一个 检查 | 更新日期: 2023-09-27 18:14:50
我遇到过这个问题,没有找到合适的方法来检查给定的X,Y点是否在任意二维多边形内。
经过几个小时后,我设法找到了一种方法,它也考虑了多边形边缘上的点作为匹配。
通过使用具有双X和双Y属性的自定义类Vector2,您可以使用以下代码来检查给定的"Position"是否在"Points"的多边形内:
public bool CheckCollision( Vector2[] Points, Vector2 Position )
{
double MinX = Points.Min( a => a.X );
double MinY = Points.Min( a => a.Y );
double MaxX = Points.Max( a => a.X );
double MaxY = Points.Max( a => a.Y );
if( Position.X < MinX || Position.X > MaxX || Position.Y < MinY || Position.Y > MaxY )
return false;
int I = 0;
int J = Points.Count() - 1;
bool IsMatch = false;
for( ; I < Points.Count(); J = I++ )
{
//When the position is right on a point, count it as a match.
if( Points[ I ].X == Position.X && Points[ I ].Y == Position.Y )
return true;
if( Points[ J ].X == Position.X && Points[ J ].Y == Position.Y )
return true;
//When the position is on a horizontal or vertical line, count it as a match.
if( Points[ I ].X == Points[ J ].X && Position.X == Points[ I ].X && Position.Y >= Math.Min( Points[ I ].Y, Points[ J ].Y ) && Position.Y <= Math.Max( Points[ I ].Y, Points[ J ].Y ) )
return true;
if( Points[ I ].Y == Points[ J ].Y && Position.Y == Points[ I ].Y && Position.X >= Math.Min( Points[ I ].X, Points[ J ].X ) && Position.X <= Math.Max( Points[ I ].X, Points[ J ].X ) )
return true;
if( ( ( Points[ I ].Y > Position.Y ) != ( Points[ J ].Y > Position.Y ) ) && ( Position.X < ( Points[ J ].X - Points[ I ].X ) * ( Position.Y - Points[ I ].Y ) / ( Points[ J ].Y - Points[ I ].Y ) + Points[ I ].X ) )
{
IsMatch = !IsMatch;
}
}
return IsMatch;
}
我希望这对你有帮助。享受吧!