2010-08-21 17 views
2

這裏是我正在研究的代碼,我希望所有的敵人自己去每個航點。然而,當一個敵人擊中航點時,所有敵人都會轉向下一個航點。我如何解決它?當一個'敵人'命中一個航點時,所有敵人都會進入隊列中的下一個航點...爲什麼?

我從main運行這個,我有一個敵人類,我已經通過隊列作爲參數,當我的敵人被創建。原來的隊列被稱爲'wayQ',我的敵人使用的複製的隊列被稱爲'way'。

編輯: 這裏是敵人階級。我修改了代碼以覆蓋主要更新方法。

class Enemy : GameObject 
{ 
    public Texture2D texture; 
    public float scale = 0.3f; 
    public Queue<Vector2> way = new Queue<Vector2>(); 
    private int atDestinationLimit = 1; 

    public Enemy() 
    { 
    } 

    public Enemy(ContentManager Content, int health, float speed, Vector2 vel, Vector2 pos, Queue<Vector2> wayQ) 
    { 
     this.Health = health; 
     this.Speed = speed; 
     this.velocity = vel; 
     this.position = pos; 
     this.IsAlive = true; 
     this.texture = Content.Load <Texture2D>("SquareGuy"); 
     this.center = new Vector2(((this.texture.Width * this.scale)/2), ((this.texture.Height * this.scale)/2)); 
     this.centPos = this.position + this.center; 
     this.way = wayQ; 
    } 

    public void Update(GameTime theGameTime) 
    { 
     if (way.Count > 0) 
     { 
      if (Vector2.Distance(centPos, way.Peek()) < atDestinationLimit) 
      { 
       float distanceX = MathHelper.Distance(centPos.X, way.Peek().X); 
       float distanceY = MathHelper.Distance(centPos.Y, way.Peek().Y); 

       centPos = Vector2.Add(centPos, new Vector2(distanceX, distanceY)); 
       way.Dequeue(); 
      } 
      else 
      { 
       Vector2 direction = -(centPos - way.Peek()); 
       direction.Normalize(); 
       velocity = Vector2.Multiply(direction, Speed); 

       centPos += velocity; 
      } 
     } 
    } 
} 

回答

0

如果沒有所述敵人使用的代碼(它似乎包含航點邏輯)很難看出。邏輯表明,一個敵人的航點似乎在所有的敵人之間共享 - 敵人的航路場可能被宣佈爲靜態的?

+0

不,我添加了敵人的班級給你看。 – Court 2010-08-21 21:39:29

7

修改您的Enemy類以擁有自己的副本的航點列表。創建一個航點列表並將其分配給每個Enemy對象,可爲每個對象提供對一個列表的引用。當你在一個航點,你在一個列表中。

+0

我已經添加了敵人的類。我有沒有創建一個副本? – Court 2010-08-21 21:39:51

+0

不可以。航點列表通過引用傳遞給您的構造函數,並且不會被克隆。 Jeff很好地捕捉到了。 – MNGwinn 2012-06-22 19:00:34

0

我改變了下面的代碼:

this.way = wayQ; 

到:

this.way = new Queue<Vector2>(wayQ); 

現在,它的偉大工程!

+1

這就是我所建議的。 – 2010-08-21 22:25:40