XNA 4.0 在按键时改变纹理

XNA 4.0 change texture on key press

我最近接触了 xna 框架,但遇到了一个问题。 这是我的代码,但没有用

    // 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);
    }

玩家总是被画成 "playerShip" (对不起我的英语)

只加载了第一个纹理,如果您要更改纹理的名称,您应该再次调用 Content.Load

但是,处理器很难继续重新加载图像,最好一次加载所有图像。所以与其回忆LoadContent()部分,你应该制作第二个Texture2D,并直接更改纹理,而不是更改目录名称。

像这样:

//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);
}