2013-11-04 33 views
0

試圖在這裏製作2D側滾動器XNA 3.1 - 不確定如何在敵人類中添加矩形

我對編程頗爲陌生。我試圖按照指南和教程沒有太多的運氣。我知道這很簡單,但我無法弄清楚。

我對遊戲中的所有不同角色都有多個類。

我對玩家將控制的主精靈角色有一個矩形。

但問題是我想在敵方精靈周圍添加矩形,這樣我就可以將碰撞添加到遊戲中。

public class enemyRocks 
{ 
    public Texture2D texture; 
    public Vector2 position; 
    public Vector2 velocity; 
    public Rectangle rockRectangle; 

    public bool isVisible = true; 

    Random random = new Random(); 
    int randX; 

    public enemyRocks(Texture2D newTexture, Vector2 newPosition) 
    { 
     texture = newTexture; 
     position = newPosition; 


     randX = -5; 
     velocity = new Vector2(randX, 0); 

    } 


    public void Update(GraphicsDevice graphics) 
    { 
     position += velocity; 

     if (position.X < 0 - texture.Width) 
      isVisible = false; 

    } 

    public void Draw(SpriteBatch spriteBatch) 
    { 
     spriteBatch.Draw(texture, position, Color.White); 
    } 
} 

我真的嘗試了很多方法,但它似乎並沒有工作。

我迄今爲止所做的一切都給了我一個「nullreferenceexception was unhandled」錯誤。

我會採取任何需要改進的批評。

謝謝你的幫助。

+0

你從哪裏得到NullReferenceException? – pinckerman

回答

1

你需要在你的精靈boundingBox的屬性

new Rectangle((int)Position.X,(int)Position.Y,texture.Width, texture.Height); 

那就要檢查一下碰撞

if (Sprite1.BoundingBox.Intersects(Sprite2.BoundingBox)) 

但要確保你使用任何紋理函數之前加載你的紋理。我想你的錯誤發生在你嘗試獲取未加載的紋理寬度的更新函數上。