Reputation: 151
I'm programming a game in processing, but I'm having the following problem: When I press the left arrow key, the character moves to the left. But if I keep the key pressed and then press jump(up arrow key) while pressing the left arrow key, when the character arrives the ground he stop the movement. This happens because somehow the Processing stop getting the pressed key after you press another. There's anyway to fix that?
Upvotes: 0
Views: 445
Reputation: 2854
There is keyTyped() but I never get it to work as described in reference... You may try it thoug... The keyPressed() is called once when a key is pressed, but not for the time it still pressed. A usual way of doing this is to use booleans called from both, keyPressed() and keyReleased() to keep track of the states you need, like:
[EDIT2] code adapted:
boolean[]keys = new boolean[5];
final int A = 0;
final int W = 1;
final int S = 2;
final int D = 3;
final int R = 4;
char keyP;
PVector p;
void setup(){
size(400,400);
p = new PVector (width/2, height/2);
}
void draw(){
background(255);
ellipse ( p.x, p.y, 10, 10);
if(keys[A]){
p.x--;
}
if(keys[W]){
p.y--;
}
if(keys[S]){
p.x++;
}
if(keys[D]){
p.y++;
}
if(keys[R]){
println("what should I do?");
}
}
void keyPressed() {
keyP = key;
switch(keyP) {
case 'A':
case 'a':
keys[A] = true;
//println("a pressionado");
break;
case 'W':
case 'w':
keys[W] = true;
//println("w pressionado");
break;
case 'S':
case 's':
keys[S] = true;
//println("s pressionado");
break;
case 'D':
case 'd':
keys[D] = true;
//println("d pressionado");
break;
case 'R':
case 'r':
keys[R] = true;
//println("r pressionado");
break;
}
}
void keyReleased(){
keyP = key;
switch(keyP){
case 'A':
case 'a':
keys[A] = false;
//println("a solto");
break;
case 'W':
case 'w':
keys[W] = false;
//println("w solto");
break;
case 'S':
case 's':
keys[S] = false;
//println("s solto");
break;
case 'D':
case 'd':
keys[D] = false;
//println("d solto");
break;
case 'R':
case 'r':
keys[R] = false;
//println("r solto");
break;
}
}
Upvotes: 0