2010-11-07 22 views
2

我正在嘗試編寫類似於Java中的Mario的遊戲,並且在運行期間讓老兄跳轉時出現問題。下面的代碼最終會做的是,當用戶按住右鍵並按下跳轉按鈕時,Mario基本上會停止運行並跳轉,所以它就像用戶已經放開並按下跳轉一樣。需要幫助按下java中的多個鍵

public void keyPressed(KeyEvent e) { 
// here I keep track of what buttons the user pressed 
    int keyCode = e.getKeyCode(); 

    if(keyCode == 37) 
     pressedKeys[0] = true; 
    else if(keyCode == 39) 
     pressedKeys[1] = true; 
    else if(keyCode == 68) 
     pressedKeys[2] = true; 

    // after I see what the user has pressed an action is carried out 
    Thread t = new Thread(this); 
    t.start(); 
} 

public void performAction() 
{ 
    // depending on what the user has pressed a certain action is performed 
    if(pressedKeys[2]==true) 
    { 
     // changes the coordinates of the character itself 
     // done in another thread so the background can continue 
     // moving as the user holds down a direction 
     Thread t = new Thread(mcControl); 
     t.start(); 
    } 
    if(pressedKeys[0]==true) 
    { 
     changeSprite(); 
     bg.moveImageForward(); 
    } 
    if(pressedKeys[1]==true) 
    { 
     changeSprite(); 
     bg.moveImageBackward(); 
    } 
} 

public void run() { 
    performAction(); 
} 

回答

1
if(keyCode == 37) 

不相關的問題,但從來沒有使用代碼這樣。大多數人不知道這個神奇數字的含義。

更好的方式來做到這一點是使用:

if(keyCode == KeyEvent.VK_???) 

現在你的代碼是自我記錄。