2012-12-04 90 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(距離<20) – Cyral

回答

1

它是否必須是20像素在屏幕上?看起來很奇怪。 你可以嘗試使用Vector2.Distance方法來計算玩家和敵人之間的歐式距離。如果距離爲20或更低,請停止敵人。如果沒有,請繼續關注玩家。