2013-02-26 66 views
0

我遇到源Rectangle問題,並且因此我的紋理不顯示在屏幕上。 當我使用繪圖方法與源爲null紋理的作品。無法在構造函數中設置紋理

我不知道這有什麼問題。

此外,如果我把這個到構造函數:source=new Rectangle((int)position.x,(int)position.Y, texture.Width/frameas, texture.Height)。我得到的錯誤

「使用關鍵字來創建一個對象」

有一個在我的Game1沒有錯誤肯定,因爲我只裝質地,更新,並繪製在那裏。

public class Player 
{ 
    public Texture2D texture; 
    public Vector2 position; 
    public int speed, width,frames, jump; 
    public float scale; 
    public Vector2 velocity; 
    public float gravity; 
    public bool hasJumped; 
    public Rectangle source; 



    public Player(int x, int y) 
    { 
     speed = 5; 
     position.X = x; 
     position.Y = y; 
     scale = 1.8f; 
     frames = 4; 
     source = new Rectangle(x,y, 30,30); 


    } 

    public void LoadContent(ContentManager Content) 
    { 
     texture = Content.Load<Texture2D>("player"); 
    } 
    public void Update(GameTime gameTime) 
    { 
     position += velocity; 
     KeyboardState keyState = Keyboard.GetState(); 
     if (keyState.IsKeyDown(Keys.D)) 
     { 
      velocity.X = 3f; 
     } 
     if (keyState.IsKeyDown(Keys.A)) 
     { 
      velocity.X = -3f; 
     } 
     if (keyState.IsKeyDown(Keys.Space) && hasJumped==false) 
     { 
      position.Y -= 10f; 
      velocity.Y = -5f; 
      hasJumped = true; 
     } 
     if (hasJumped == true) 
      velocity.Y += 0.15f; 
     else 
      velocity.Y = 0f; 
    } 
    public void Draw(SpriteBatch spriteBatch) 
    { 
     spriteBatch.Draw(texture, position, source, Color.White, 0f, Vector2.Zero, scale, SpriteEffects.None, 0f); 
    } 
} 
} 
+0

請您提供您在構造函數中'new'關鍵字描述錯誤的一些更詳細?也請在播放器構造函數中發佈播放器紋理的大小以及您期望得到的源矩形(以及您實際獲得的內容)的大小。 – user1306322 2013-02-26 12:51:27

+0

源=新Rectangle((int)position.x,(int)position.Y,(int)texture.Width/frameas,(int)texture.Height) – 2013-02-26 13:07:39

+0

@JackGajanan可以在問題中找到,我問爲**一些更詳細的**。 – user1306322 2013-02-26 13:14:07

回答

1

你不能在你的構造函數中引用texture,因爲它還不存在。它沒有設置爲實際值,直到您在LoadContent()中加載紋理爲止,所以當您嘗試使用它構建矩形時,它會拋出NullReferenceException

這條線後,即可製作源矩形:

texture = Content.Load<Texture2D>("player"); 
+0

你是對的,但它仍然不顯示屏幕上的紋理。可以說我的紋理(瓦片)大小是100/50有2幀,我想顯示第一個。我創建了: Rectangle source = new Rectangle((int)position.X,(int)position.Y,texture.Width/frames,texture.Height) (就像我在上面的代碼中所做的那樣)並且它沒有顯示紋理在屏幕上很奇怪,因爲它應該工作 – Cam3ll 2013-02-26 14:50:29

+0

'position'的價值是什麼?你似乎用它來表示兩個不同的東西:精靈在紋理上的位置,以及玩家在屏幕上的位置。 – 2013-02-26 15:21:00

+0

position =玩家在屏幕上的位置..可以說它的(100,100) – Cam3ll 2013-02-26 15:54:46

相關問題