我正在基于羊群制作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。我更喜欢使用方向向量而不是角度,因此您可以将DOT产品操作用于这种趋势更快的东西,并且您不必担心规范范围之外的角度。

以下代码应达到您所追求的结果:

    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;
    }

其他提示

我认为您想测试+/-斜角,而不仅仅是 +(即 angleDifference >= -ViewAngle/2 && angleDifference <= ViewAngle/2)。或使用绝对值。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top