2013-02-26 69 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

相关问题