按键改变纹理

时间:2013-12-12 00:32:29

标签: c# xna xna-4.0 keyboard-events

这是我的方法来获取键盘状态并根据按下的键更改纹理。

private void CheckKeyboardAndUpdateMovement()
{
    KeyboardState keyboardState = Keyboard.GetState();
    if (keyboardState.IsKeyUp(Keys.Left)) { ChangeTexture(1); }
    if (keyboardState.IsKeyUp(Keys.Right)) { ChangeTexture(2); }
    if (keyboardState.IsKeyDown(Keys.Left))
    {
        Movement -= Vector2.UnitX;
        ChangeTexture(3);
    }
    if (keyboardState.IsKeyDown(Keys.Right))
    {
        Movement += Vector2.UnitX;
        ChangeTexture(4);
    }
    if ((keyboardState.IsKeyDown(Keys.Space) || keyboardState.IsKeyDown(Keys.Up)) && IsOnFirmGround())
    {
        Movement = -Vector2.UnitY * JumpHeight;
    }
}

如果按下方向,它会起作用,但是当没有按下任何东西时它没有自己的工作(只是因为IsKeyUp都是真的)。只有案例的顺序可以防止在移动精灵时显示静态纹理... 我的问题是,我怎样才能彻底解决这个问题呢?我已经有了一个想法,但我根本不喜欢它......

2 个答案:

答案 0 :(得分:0)

我想到的最糟糕的解决方案是,当按下最后一个键时存储精灵方向并检查下一个更新,但是它会变得更加混乱,键和纹理我会#39 ;我必须控制......

// Having a "bool leftDirectionOnLastMovement;" (worst name ever seen)
private void CheckKeyboardAndUpdateMovement()
{
    KeyboardState keyboardState = Keyboard.GetState();
    if (keyboardState.IsKeyUp(Keys.Left) && leftDirectionOnLastMovement)
        ChangeTexture(1);
    if (keyboardState.IsKeyUp(Keys.Right) && !leftDirectionOnLastMovement)
        ChangeTexture(2);
    if (keyboardState.IsKeyDown(Keys.Left))
    {
        Movement -= Vector2.UnitX;
        ChangeTexture(3);
        leftDirectionOnLastMovement = true;
    }
    }
    if (keyboardState.IsKeyDown(Keys.Right))
    {
        Movement += Vector2.UnitX;
        ChangeTexture(4);
        leftDirectionOnLastMovement = false;
    }
    }
    if ((keyboardState.IsKeyDown(Keys.Space) || keyboardState.IsKeyDown(Keys.Up)) && IsOnFirmGround())
    {
        Movement = -Vector2.UnitY * JumpHeight;
    }
}

我真的希望有人会建议我更好的方法来做到这一点......

答案 1 :(得分:0)

如果您想要其他解决方案,但仍然与您的解决方案相似。

enum Direction { Left = 1, Right = 2}
Direction dir = Direction.Left; //or whatever

private void CheckKeyboardAndUpdateMovement()
{
    KeyboardState keyboardState = Keyboard.GetState();

    ChangeTexture((int)dir);
    if (keyboardState.IsKeyDown(Keys.Left))
    {
        Movement -= Vector2.UnitX;
        ChangeTexture(3);
        dir = Direction.Left;
    }
    if (keyboardState.IsKeyDown(Keys.Right))
    {
        Movement += Vector2.UnitX;
        ChangeTexture(4);
        dir = Direction.Right;
    }
    if ((keyboardState.IsKeyDown(Keys.Space) || keyboardState.IsKeyDown(Keys.Up)) && IsOnFirmGround())
    {
        Movement = -Vector2.UnitY * JumpHeight;
    }
}

你可以用行走精灵做类似的事情。