【问题标题】:XNA 4.0 change texture on key pressXNA 4.0 在按键时更改纹理
【发布时间】:2018-10-09 18:10:13
【问题描述】:

我最近进入了 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” (对不起我的英语)

【问题讨论】:

  • 你必须再次调用 LoadContent()。

标签: c# xna textures


【解决方案1】:

仅加载第一个纹理,如果要更改纹理名称,则应再次调用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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    • 2012-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多