Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Processing keyPressed()

basically I have to use Processing for a project (not out of choice) and have come across a problem regarding the pressing of multiple keys at once. In the keyPressed()function, I have multiple conditionals, each mapping a key to an action. This is all well and good, but supposing I want to press multiple keys at once?

Any suggestions?

Thanks.

like image 248
Jack H Avatar asked Jun 22 '26 09:06

Jack H


1 Answers

Create an array. Assign a numeric value to each key that you are checking, then turn on the corresponding value in the array on or off whenever a key is pressed or released. Then in the draw() you check the values of the array to see which are on and off at any given instant.

boolean[] keys = new boolean[4];
final int A = 0;
final int D = 1;
final int W = 2;
final int S = 3;

void setup() {

}

void draw() {

 if (keys[D]) {
   // do something;
 } 
if (keys[A]) {
   // do something;
 } 
if (keys[W]) {
   // do something;
 } 
if (keys[S]) {
   // do something;
 } 

} // end of draw()


void keyPressed() {
   int mybutton = key;  // the ascii value of the key that was pushed

     switch (mybutton) {
      case 101: 
        keys[D] = true;
        break;
      case 97: 
        keys[A] = true;
        break;
      case 44:
        keys[W] = true;
        break;
      case 111:
        keys[S] = true;
        break;
    } // end switch

} // end keyPressed

void keyReleased() {
switch (mybutton) {
      case 101: 
        keys[D] = false;
        break;
      case 97: 
        keys[A] = false;
        break;
      case 44:
        keys[W] = false;
        break;
      case 111:
        keys[S] = false;
        break;
    } // end switch

} // end keyReleased
like image 188
Chris Avatar answered Jun 25 '26 01:06

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!