[英]XNA field of view in 2D
我正在开发基于植绒的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是一个弧度值,我曾尝试使用该弧度值以获得正确的效果,但这主要是导致将所有座席分配为领导者。
谁能指出我正确的方向,以检测一个实体是否在另一个实体的“视锥”内?
我认为您想测试+/-角度,而不仅仅是+(即angleDifference >= -ViewAngle/2 && angleDifference <= ViewAngle/2
)。 或使用绝对值。
您需要将输入标准化为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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.