Archived

This topic is now archived and is closed to further replies.

shtkn

[java] Key Event problems

Recommended Posts

shtkn    122
Hey all, I''m planning to make a Street Fighter - ish game, and am in need of some help. Obviously, the game will be in java, and as such I use the Key Event listener to listen for keyboard presses. However, the problem is that the keyboard presses can only detect one key at a time. So essentially, I am only limited to having one character move at a time only. Is there any way around this problem? My teacher said that using keys like Control, Alt, Shift would do the trick, but I want to avoid that so the player can have a keyboard configuration that makes sense. Any help would be appreciated, Kevin Hsu

Share this post


Link to post
Share on other sites
mill-o    122
i had the same problem with my car game. i couldn't accelerate and turn the car at the same time.

so when i got an KeyEvent which was VK_UP, i simply put a boolean in my car class that it should accelerate, as in car.up(true) and then the car would move etc.

    
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();

// controls

if (key == e.VK_DOWN)
car1.down(true);
if (key == e.VK_UP)
car1.up(true);
// and so on

}

// and this is in my car class

public void move(int dt) {
if (up)
accelerate(dt);
if (down)
brake(dt);
// and so on

}


Edited by - mill-o on December 11, 2001 1:08:16 PM

Share this post


Link to post
Share on other sites
Kanzetsu    122
Create an array of booleans called something like keysDown, and on keyPressed() set the item in the array corresponding to the pressed key to true. On keyReleased, set it to false. This way, you won't have the "type delay" problem and you can handle multiple pressed keys.

      
boolean [] keysDown;

...

keysDown = new boolean[256];
for (int i = 0; i < 256; i++)
keysDown[i] = false;

...

void keyPressed(KeyEvent e) {
keysDown[(e.getKeyCode())] = true;
}
void keyReleased(KeyEvent e) {
keysDown[(e.getKeyCode())] = false;
}
boolean keyIsDown(int key) {
return keysDown[key];
}


// Kanzetsu

UPDATE: oops, looks like I had messed up the return type of keyIsDown()

Edited by - Kanzetsu on December 17, 2001 5:20:45 AM

Share this post


Link to post
Share on other sites