代码之家  ›  专栏  ›  技术社区  ›  Cam3ll

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

  •  0
  • Cam3ll  · 技术社区  · 13 年前

    我对来源有问题 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);
        }
    }
    }
    
    1 回复  |  直到 11 年前
        1
  •  1
  •   Cole Campbell    13 年前

    你不能引用 texture 因为它还不存在。在加载纹理之前,它不会设置为实际值 LoadContent() ,所以当你试图用它来构建你的矩形时,它会抛出一个 NullReferenceException .

    在此行之后创建源矩形:

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