按下C#XNA后检查是否释放了一个键

Bas*_*Bas 0 c# xna

我得到了一些代码来检查玩家是否按下某个键.当玩家按下空格键时,精灵会上升.但我正试图在释放钥匙时将精灵设置回地面.这是我提出的代码:

keystate = Keyboard.GetState();
if (keystate.IsKeyDown(Keys.Right))
     playerPosition.X += 2.0f;
else if (keystate.IsKeyDown(Keys.Left))
     playerPosition.X -= 2.0f;
else if (keystate.IsKeyDown(Keys.Space))
{
   if (keystate.IsKeyDown(Keys.Space))
       playerPosition.Y -= 6.0f;
   else if (keystate.IsKeyUp(Keys.Space))
        playerPosition.Y += 6.0f;
}
Run Code Online (Sandbox Code Playgroud)

当没有按空格键时,我不希望精灵被移动.任何解决方案将不胜感激?

编辑:精灵确实向上移动,但永远不会下降!

Mon*_*aft 6

你可以存储oldstate:

KeyboardState newState = Keyboard.GetState();  // get the newest state

// handle the input
if(newState.IsKeyDown(Keys.Space) && oldState.IsKeyUp(Keys.Space))
{
    playerPosition.Y += 6.0f;
}
if(newState.IsKeyUp(Keys.Space) && oldState.IsKeyDown(Keys.Space))
{
    playerPosition.Y -= 6.0f;
}

oldState = newState;  // set the new state as the old state for next time
Run Code Online (Sandbox Code Playgroud)

这应该成功.