射弹跟踪代码难度大

时间:2010-05-12 02:50:52

标签: c# tracking trigonometry

我在游戏中为一个射弹类编写了一些代码,如果可以的话,它会跟踪目标:

            if (_target != null && !_target.IsDead)
            {
                Vector2 currentDirectionVector = this.Body.LinearVelocity;
                currentDirectionVector.Normalize();
                float currentDirection = (float)Math.Atan2(currentDirectionVector.Y, currentDirectionVector.X);
                Vector2 targetDirectionVector = this._target.Position - this.Position;
                targetDirectionVector.Normalize();
                float targetDirection = (float)Math.Atan2(targetDirectionVector.Y, targetDirectionVector.X);
                float targetDirectionDelta = targetDirection - currentDirection;
                if (MathFunctions.IsInRange(targetDirectionDelta, -(Info.TrackingRate * deltaTime), Info.TrackingRate * deltaTime))
                {
                    Body.LinearVelocity = targetDirectionVector * Info.FiringVelocity;
                }
                else if (targetDirectionDelta > 0)
                {
                    float newDirection = currentDirection + Info.TrackingRate * deltaTime;
                    Body.LinearVelocity = new Vector2(
                        (float)Math.Cos(newDirection),
                        (float)Math.Sin(newDirection)) * Info.FiringVelocity;
                }
                else if (targetDirectionDelta < 0)
                {
                    float newDirection = currentDirection - Info.TrackingRate * deltaTime;
                    Body.LinearVelocity = new Vector2(
                        (float)Math.Cos(newDirection),
                        (float)Math.Sin(newDirection)) * Info.FiringVelocity;
                }
            }

这有时会起作用,但取决于与目标射弹的相对角度,转而远离目标。我很难过;有人能指出我代码中的缺陷吗?

更新:考虑它和尝试的东西让我得出的结论是,当方向(以弧度为单位)低于0且当前射弹角度大于0时,它与某些事情有关。

1 个答案:

答案 0 :(得分:1)

变量targetDirectionDelta并不总是目标的最短方向。如果targetDirectionDelta的绝对值大于PI弧度,则抛射物将出现远离目标的情况。转向另一个方向的时间较短且预期。

示例:

currentDirection = 2
targetDirection = -2

射弹可以转-4弧度(负方向),或2 *(PI-2)弧度(约2.2弧度)(正方向)。

对于这种情况,你的代码总是计算更长的方向,但你期望抛射物转向更短的方向:

targetDirectionDelta = targetDirection - currentDirection