This site requires JavaScript, please enable it in your browser!
Greenfoot back
DerNait
DerNait wrote ...

2023/7/25

KeyListener

DerNait DerNait

2023/7/25

#
Hello, I wanted to know if there is a way to implement the java KeyListener to greenfoot. I want to use it because I am trying to make a two-player system, the thing is that I want both players to be able to press different keys at the same time. I don't like to use isKeyDown because I want the key to be registered only once, not a few times in a frame that is what usually happens when I use isKeyDown.
danpost danpost

2023/7/25

#
DerNait wrote...
I want both players to be able to press different keys at the same time. I don't like to use isKeyDown because I want the key to be registered only once, not a few times in a frame that is what usually happens when I use isKeyDown.
There are two ways around this. The first is by simply using getKey instead of isKeyDown. However, I reserve the use of it for non-game play operations. A better way may be to add a boolean to track the state of each key being used. Use the following structure to catch changes in the state of a set of keys (example used 'd' and 'left" (arrow) keys):
// instance fields
private boolean dDown;
private boolean leftDown;

// code in act
int downCount = (dDown ? 1 : 0)+(leftDown ? 1 : 0);
downCount = downCount%2; // to avoid repeating each act if both keys are already down
if (dDown != Greenfoot.isKeyDown("d")) {
    dDown = ! dDown;
    downCount += dDown ? 1 : 0;
}
if (leftDown != Greenfoot.isKeyDown("left")) {
    leftDown = ! leftDown;
    downCount += leftDown ? 1 : 0;
}
if (downCount == 2) { // acts once each instance a change in key state ends up with both keys down
    // do something
}
DerNait DerNait

2023/7/26

#
That helped a lot, thank you!
You need to login to post a reply.