I recently wrote some code that deals with tracking which keys are down in a neat way:
Here’s the code that counts:
void keyPressed(){
k(true);
}
void keyReleased(){
k(false);
}
int[] ks = {LEFT, RIGHT};
boolean[] kd = {false,false};
void k(boolean b){
for( int i = 0; i < ks.length; i++){
if( ks[i] == keyCode ) kd[i] = b;
}
}
Notice that this defines two arrays. ks
is the keys that you wish to track. kd
is a boolean array that records if the key in ks
at the same index is held down.
You can use this in your conditional checks:
if( kd[0] && kd[1] ){ // If LEFT arrow and RIGHT arrow are held down at the same time.
Notice that this is using the logical AND operator, &&
, not the addition operator +
!