开发者

Need help with pressing multiple keys in java

I'm trying to code a game similar to Mario in Java and am having problems with making the dude jump while he is running. What the below code ends up doing is, as the user is holding down right and presses the jump button, Mario basically stops running and jumps, so its like the user has let go of right and pressed jump.

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() {
    performActi开发者_开发问答on();
}


if(keyCode == 37) 

Not related to your problem, but NEVER use code like that. Most people don't know what that magic number means.

The better way to do this is to use:

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

Now your code is self documenting.


You want to take a look at How to Write a Key Listener. The KeyEvent object has several methods for learning what modifier keys and mouse buttons were pressed at the time the event was generated.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜