Search code examples
c#xnatextures

XNA 4.0 change texture on key press


I've been getting into xna framework recently and I came across a problem. This's my code and it didn't work

    // Constructor
    public Player()
    {
        texture = null;
        position = new Vector2(350, 900);
        moveSpeed = 10;
        textureTitle = "playerShip";
    }

    // Load
    public void LoadContent(ContentManager Content)
    {
        texture = Content.Load<Texture2D>(textureTitle);
    }

    // Update
    public void Update(GameTime gameTime)
    {
        KeyboardState curKeyboardState = Keyboard.GetState();

        if (curKeyboardState.IsKeyDown(Keys.W))
        {
            position.Y = position.Y - moveSpeed;
            textureTitle = "playerShip2";
        }
            if (curKeyboardState.IsKeyDown(Keys.S))
            position.Y = position.Y + moveSpeed;
        if (curKeyboardState.IsKeyDown(Keys.A))
            position.X = position.X - moveSpeed;
        if (curKeyboardState.IsKeyDown(Keys.D))
            position.X = position.X + moveSpeed;

    }

    // Draw
    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(texture, position, Color.White);
    }

player's always being drawn as "playerShip" (sorry for my English)


Solution

  • Only the first texture is loaded, if you're changing the name of the texture, you should call Content.Load again.

    However, it's harder for the processor to keep reloading the images, and it's better done if the images are all loaded at once. So instead of recalling the LoadContent() part, you should make a second Texture2D, and change the texture directly, instead of changing the directory name.

    Something like this:

    //add this to your public variables
    public Texture2D currentTexture = null;
    
    // Load
    public void LoadContent(ContentManager Content)
    {
        texture  = Content.Load<Texture2D>("playerShip");
        texture2 = Content.Load<Texture2D>("playerShip2");
        currentTexture = texture;
    }
    
    // Update
    public void Update(GameTime gameTime)
    {
        KeyboardState curKeyboardState = Keyboard.GetState();
        if (curKeyboardState.IsKeyDown(Keys.W))
        {
            currentTexture = texture2;
        }
        //...
    }
    
    // Draw
    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(currentTexture, position, Color.White);
    }