2012-10-26 45 views
2

我是編程世界的初學者,現在我正在嘗試使用C#編寫XNA,現在我正在開發基本的遊戲,其中玩家是飛機或太空船,而且您必須拍攝向下流星。XNA 2D基本碰撞列表

目前我正在嘗試盒子碰撞檢測,我不能完全弄清楚它,我不知道如何獲得列表中每一項的位置,我需要你的幫助!

所以基本上我有一個shiptexture和meteortexture。模型紋理繪製10次,並獲得隨機位置。我想在每個流星周圍製作矩形,但我不知道如何。我試着用下面顯示的foreach循環,但當我與它碰撞時,只有一顆流星起作用。對不起,如果我的英語不是最好的,我感謝大家的幫助!

List<Vector2> meteor_pos = new List<Vector2>(); 

       //loadcontent 
      for (int i = 0; i < 10; i++) 
      { 
       meteor_pos.Add(new Vector2(myRnd.Next(800), myRnd.Next(600))); 
       double tmp_angle = (myRnd.Next(1000) * Math.PI * 2)/1000.0; 
       double tmp_speed = 0.5 + 3.0 * (myRnd.Next(1000)/1000.0); 
       meteor_speed.Add(new Vector2((float)(tmp_speed * Math.Cos(tmp_angle)), 
       (float)(tmp_speed * Math.Sin(tmp_angle)))); 
      } 

       //protected override void Update(GameTime gameTime) 
       for (int i = 0; i < meteor_pos.Count; i++) 
       { 
        meteor_pos[i] += meteor_speed[i]; 
        Vector2 v = meteor_pos[i]; 
        //Outside the screen? 
        if (v.X < -80) 
         v.X = graphics.GraphicsDevice.Viewport.Width + 80; 
        if (v.X > graphics.GraphicsDevice.Viewport.Width + 80) 
         v.X = -80; 
        if (v.Y < -60) 
         v.Y = graphics.GraphicsDevice.Viewport.Height + 60; 
        if (v.Y > graphics.GraphicsDevice.Viewport.Height + 60) 
         v.Y = -60; 
        //Uppdate the list 
        meteor_pos[i] = v; 

       } 
       foreach (var item in meteor_pos)  
       { 
        meteor_rect = new Rectangle((int)item.X, (int)item.Y, gfx_meteor.Width, gfx_meteor.Height); 
       } 

       gfx_rect = new Rectangle((int)position.X, (int)position.Y, gfx.Width, gfx.Height); 

       if (gfx_rect.Intersects(meteor_rect)) 
       { 
        position.X = 0; 
        position.Y = 0; 
       } 

    //protected override void Draw(GameTime gameTime) 

       for (int i = 0; i < meteor_pos.Count; i++) 
      { 
       spriteBatch.Draw(gfx_meteor, meteor_pos[i], null, Color.White, 0, 
       new Vector2(gfx_meteor.Width/2, gfx_meteor.Height/2), 1.0f, SpriteEffects.None, 0); 
      }} 

回答

1

你的做法是非常令人迷惑,你會想創建一個類,以最低的可能是處理的位置和其他的一些基本信息精靈類。

但是,要解決您當前的問題,您將在foreach循環中覆蓋meteor_rect的值,然後在最後一次僅檢查碰撞。

所以切換您的代碼如下所示:

gfx_rect = new Rectangle((int)position.X, (int)position.Y, gfx.Width, gfx.Height); 

foreach (var item in meteor_pos)  
    { 
     meteor_rect = new Rectangle((int)item.X, (int)item.Y, gfx_meteor.Width, gfx_meteor.Height); 

     if (gfx_rect.Intersects(meteor_rect)) 
      { 
       position.X = 0; 
       position.Y = 0; 
      } 
    } 

但就像我說請找了一個基本的教程,以幫助你了:)

+0

會做,感謝您的幫助,但! – user1775668