2010-05-12 93 views
0

我写了一些代码在我的游戏抛射类,使得如果可以它跟踪目标:困难弹丸的跟踪代码

  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

的结论变量targetDirectionDelta并不总是最短的目标方向。如果targetDirectionDelta的绝对值大于PI弧度,则会显示抛射体正在离开目标。转向另一个方向的时间更短且预期。

实施例:

currentDirection = 2 
targetDirection = -2 

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

对于这种情况,你的代码总是计算较长方向,但你期待弹丸向着较短方向:

targetDirectionDelta = targetDirection - currentDirection

+0

是,不知何故,我忘了说了这一点。我通过添加一个检查来解决它,看看'targetDirectionDelta'是否高于pi或低于-pi首先,这告诉我,否则我会走很长的路。 – RCIX 2010-05-12 06:52:07