如果你只是檢查IsKeyDown
每一幀,它會說它是在每個幀下來,它被按下。在每秒60幀的情況下,按下一個按鍵會導致它在幾幀中處於關閉狀態。因此,在每一幀你都在移動你的角色!當你放開鑰匙時 - 他會移動幾個方塊。
如果要檢測每個按鍵(進入「向下」狀態的關鍵),你需要的東西是這樣的:
KeyboardState keyboardState, lastKeyboardState;
bool KeyPressed(Keys key)
{
return keyboardState.IsKeyDown(key) && lastKeyboardState.IsKeyUp(key);
}
override void Update(GameTime gameTime)
{
lastKeyboardState = keyboardState;
keyboardState = Keyboard.GetState();
if(KeyPressed(Keys.Right)) { /* do stuff... */ }
}
但是,如果你想添加一個「重複效應」按住時關鍵(如在打字會發生什麼),你需要統計的時間 - 是這樣的:
float keyRepeatTime;
const float keyRepeatDelay = 0.5f; // repeat rate
override void Update(GameTime gameTime)
{
lastKeyboardState = keyboardState;
keyboardState = Keyboard.GetState();
float seconds = (float)gameTime.ElapsedGameTime.TotalSeconds;
if(keyboardState.IsKeyDown(Keys.Right))
{
if(lastKeyboardState.IsKeyUp(Keys.Right) || keyRepeatTime < 0)
{
keyRepeatTime = keyRepeatDelay;
// do stuff...
}
else
keyRepeatTime -= seconds;
}
}
他正在執行基於網格/瓦片的移動,而不是連續的。 – JMRboosties 2012-04-27 20:53:50