2012-12-04 2 views
-3

대원이 플레이어를 따라 가서 20 픽셀 이내에서 멈추도록하려고합니다. Vector2.Lerp()를 비롯한 여러 알고리즘을 시도했습니다. 메소드를 시도하고 고치지 만 빌드를 계속 파괴합니다. 어떤 도움이라도 대단히 감사하겠습니다. 코드는 다음과 같습니다.XNA의 플레이어를 따라 와서 20 픽셀 이내에서 멈춤

public void Update(GameTime gameTime) 
{ 
    if (this.IsAlive) 
    { 
     float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds; 
     double distanceToPlayer = Math.Sqrt(Math.Pow(Level.Player.Position.X - this.Position.X, 2) + Math.Pow(Level.Player.Position.Y - this.Position.Y, 2)); 

     // Calculate tile position based on the side we are walking towards. 
     float posX = Position.X + localBounds.Width/2 * (int)direction; 
     int tileX = (int)Math.Floor(posX/Tile.Width) - (int)direction; 
     int tileY = (int)Math.Floor(Position.Y/Tile.Height); 

     if (waitTime > 0) 
     { 
      // Wait for some amount of time. 
      waitTime = Math.Max(0.0f, waitTime - (float)gameTime.ElapsedGameTime.TotalSeconds); 
      if (waitTime <= 0.0f) 
      { 
       // Then turn around. 
       direction = (FaceDirection)(-(int)direction); 
      } 
     } 
     else 
     { 
      // If we are about to run into a wall or off a cliff, start waiting. 
      if (Level.GetCollision(tileX + (int)direction, tileY - 1) == TileCollision.Impassable || Level.GetCollision(tileX + (int)direction, tileY) == TileCollision.Passable) //is the enemy is close and is not attacking, attack and turn! 
      { 
       waitTime = MaxWaitTime; 
      } 
      else 
      { 
       // Move in the current direction. 
       Vector2 velocity = new Vector2((int)direction * MoveSpeed * elapsed, 0.0f); 
       position = position + velocity; 
      } 
     } 
     dtAttack += gameTime.ElapsedGameTime; 
     AttackPlayer(); 
    } 
    else 
    { 
     dt += gameTime.ElapsedGameTime; 
     if (dt.TotalSeconds > (sprite.Animation.FrameCount * sprite.Animation.FrameTime)) 
      this.Remove = true; 
    } 
} 
+1

무엇이 오류입니까? – mbeckish

+1

시도하고 수정하려면 .. 뭐라고 요? 또한, 위치 사이의 거리를 얻으려면'Vector2.Distance' 만 할 수 있습니다. 어느 때까지 멈추고 싶다면, if (distance <20) – Cyral

답변

1

화면에서 20 픽셀이어야합니까? 이상하게 보입니다. Vector2.Distance 메서드를 사용하여 플레이어와 적 사이의 유클리드 거리를 계산할 수 있습니다. 거리가 20 이하이면 적을 중지하십시오. 그렇지 않은 경우 계속 플레이어를 따라 잡으십시오.

관련 문제