0

我的来源有问题,Rectangle因此我的纹理没有显示在屏幕上。当我使用源为 null 的 Draw 方法时,纹理有效。

我不知道这有什么问题。

另外,如果我将其放入构造函数中: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);
    }
}
}
4

1 回答 1

1

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

在此行之后创建源矩形:

texture = Content.Load<Texture2D>("player");
于 2013-02-26T14:39:55.490 回答