Keyboard buttons

i am trying to make a program that has a two shapes that move around with keyboard buttons i am somewhat new to coding and do not know how to make the keyboard recognize two different keys at the same time this is what i currently have:

float  R = 500;
float  U = 500;
float  r;
float  u;
void setup(){
 
  size(1000,1000);
  
}
void draw(){
  
  
  R=constrain(R,0,width-30);

   U=constrain(U,0,height-30);
 move();
 
  rect(R,U,30,30);
  ellipse(r,u,30,30);
  
}
void move(){
  if(keyPressed){
    if(keyCode == LEFT+RIGHT){
      R=R+5;
      U=U+5;
    }
   if (keyCode == LEFT) {
    R=R-5;
  }
  if(keyCode == RIGHT) {
    R=R+5;
  }
  if(keyCode == UP) {
    U=U-5;
  }
  if(keyCode == DOWN) {
    U=U+5;
  }
    if (key == 'w') {
    u=u-5;
  }
  if(key == 'a') {
    r=r-5;
  }
  if(key == 's') {
    u=u+5;
  }
  if(key == 'd') {
    r=r+5;
  }
  }
}
1 Like

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 +!

1 Like

If you are doing more than a few keys, another general option is to use implement @TfGuy44’s boolean approach using a HashMap.

import java.util.Map;
HashMap<Character,Boolean> flags = new HashMap<Character,Boolean>();

Any key that gets pressed, put it in the map with a true… any key that gets released, take it out with a false.

void keyPressed(){
  flags.put(key, Boolean.TRUE);
}
void keyReleased(){
  flags.put(key, Boolean.FALSE);
}

This can be used for simultaneous keypresses – or for a large collection of toggles:

void keyReleased(){
  if(flags.get(key)!=null){
    flags.put(key, !(flags.get(key)));
  } else {
    flags.put(key, Boolean.TRUE);
  }
}

http://Studio.ProcessingTogether.com/sp/pad/export/ro.9cfU11egvzT6G

Thanks @GoToLoop. Please post some text description when you post links.