我正在 XNA 中开发基于植绒的 2D 游戏。我已经实现了 Craig Reynold 的集群技术,现在我想动态地为该组分配一个领导者以引导它朝着目标前进。
为此,我想找到一个前面没有任何其他代理的游戏代理并使其成为领导者,但我不确定这方面的数学原理。
目前我有:
Vector2 separation = agentContext.Entity.Position - otherAgent.Entity.Position;
float angleToAgent = (float) Math.Atan2(separation.Y, separation.X);
float angleDifference = Math.Abs(agentContext.Entity.Rotation - angleToAgent);
bool isVisible = angleDifference >= 0 && angleDifference <= agentContext.ViewAngle;
agentContext.ViewAngle 是一个弧度值,我尝试使用它来尝试获得正确的效果,但这主要导致所有代理都被指定为领导者。
任何人都可以指出正确的方向来检测一个实体是否在另一个实体的“锥形”视野内吗?
最佳答案
您需要规范化 Atan2 函数的输入。此外,减去角度时必须小心,因为结果可能超出 pi 到 -pi 的范围。我更喜欢使用方向向量而不是角度,因此您可以对这类事情使用点积运算,因为它往往更快,而且您不必担心超出规范范围的角度。
下面的代码应该能达到你想要的结果:
double CanonizeAngle(double angle)
{
if (angle > Math.PI)
{
do
{
angle -= MathHelper.TwoPi;
}
while (angle > Math.PI);
}
else if (angle < -Math.PI)
{
do
{
angle += MathHelper.TwoPi;
} while (angle < -Math.PI);
}
return angle;
}
double VectorToAngle(Vector2 vector)
{
Vector2 direction = Vector2.Normalize(vector);
return Math.Atan2(direction.Y, direction.X);
}
bool IsPointWithinCone(Vector2 point, Vector2 conePosition, double coneAngle, double coneSize)
{
double toPoint = VectorToAngle(point - conePosition);
double angleDifference = CanonizeAngle(coneAngle - toPoint);
double halfConeSize = coneSize * 0.5f;
return angleDifference >= -halfConeSize && angleDifference <= halfConeSize;
}
关于c# - XNA 二维视野,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4133061/