2014-08-29 44 views
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; 
} 

。 任何解決方案將不勝感激?

編輯:精靈確實向上移動,但從未落下!

+0

在第二個else中,如果您要檢查Space鍵是否關閉,然後檢查Space鍵是否打開,則永遠不會出現這種情況。 – Measuring 2014-08-29 16:41:05

回答

2

您在空格鍵上檢查了IsKeyUp中的一個子句,只有當空格鍵關閉時纔會進入該子句!

擺脫所有冗餘else語句,並做重點了一個額外的檢查停靠玩家移動,如果它擊中地面,所以像:

keystate = Keyboard.GetState(); 

if (keystate.IsKeyDown(Keys.Space) && playerPosition.Y >= MinYPos) 
{ 
     playerPosition.Y -= 6.0f; 
} 

if (keystate.IsKeyUp(Keys.Space) && playerPosition.Y <= MaxYPos) 
{ 
     playerPosition.Y += 6.0f; 
} 
4

你可以存儲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 

而且應該解決。