无法在构造函数中设置纹理

时间:2013-02-26 12:45:50

标签: c# xna

我遇到了源Rectangle的问题,因此我的纹理没有显示在屏幕上。 当我使用Draw方法将source作为null时,纹理可以正常工作。

我不知道这有什么问题。

此外,如果我将其放入构造函数中:source=new Rectangle((int)position.x,(int)position.Y, texture.Width/frameas, texture.Height)。我收到了错误

  

“使用 new 关键字创建对象”

我的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);
    }
}
}

1 个答案:

答案 0 :(得分:1)

您无法在构造函数中引用texture,因为它尚不存在。在LoadContent()加载纹理之前,它不会设置为实际值,因此当您尝试使用它来构建矩形时,它会抛出NullReferenceException

在此行之后创建源矩形:

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