2010-05-12 10 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 라디안보다 큰 경우, 발사체가 표적에서 멀어지고있는 것처럼 보입니다. 다른 방향으로 돌리는 것이 더 짧고 예상됩니다.

예 : 발사체 (음의 방향) -4- 라디안 바꿀 수

currentDirection = 2 
targetDirection = -2 

또는 2 * (PI-2) (양의 방향) 라디안 (약 2.2 라디안). 이 경우를 들어

, 당신의 코드는 항상 긴 방향을 계산,하지만 당신은 발사체가 짧은 방향으로 설정하는 기대됩니다

targetDirectionDelta = targetDirection - currentDirection

+0

예, 어떻게 든 내가 이런 말을 잊어 버렸습니다. 나는'targetDirectionDelta'가 pi보다 먼저 있는지, 아니면 -pi보다 먼저 있는지를 확인하는 체크를 덧붙임으로써 해결했다. 그렇지 않으면 나는 먼 길을 택할 것임을 알았다. – RCIX