1

I'm using processing (java) and I'm trying to use an array called input to easily handle keypresses. Here's my code for that:

boolean input[] = {};

void keyPressed() {
    input[keyCode] = true;
}

void keyReleased() {
    input[keyCode] = false;
}

And so, if this code worked, I could just call this

if (input[32]) { //32 == SPACE
    //Do something
}

And the conditional would result to true if the key were pressed, and the statement would get executed, otherwise, it would result to false if the key were released.

However, I'm getting this error:

main.pde:1:1:1:1: Syntax Error - You may be mixing static and active modes.

Why is this?

Thanks for any help.

Scollier
  • 575
  • 6
  • 19
  • Does this answer your question? [Processing 'It looks like you're mixing "active" and "static" modes.'](https://stackoverflow.com/questions/6658827/processing-it-looks-like-youre-mixing-active-and-static-modes) – CollinD May 22 '22 at 23:52
  • I've already seen this question, and tried to fix it, but I'm not sure how it can help with my problem. – Scollier May 23 '22 at 00:18

1 Answers1

2

The following demo will trap spacebar presses. If you want to trap presses for multiple keys you would need to use an array of integers instead of booleans, eg int input[] = new int[4]; then iterate the array when keys are pressed (see second example). Keep in mind that some keys are coded and others are not, eg arrow keys are coded and it takes different code to trap them.

boolean spaceBarPressed = false;

void setup(){
}

void draw(){
  if(spaceBarPressed){
    println("Space bar pressed.");
  } else {
    println("Space bar released.");
  }
}

void keyPressed() {
  if(key == 32){
    spaceBarPressed = true;
  }
}
  
void keyReleased() {
    if(key == 32){
    spaceBarPressed = false;
  }
}

Second Example for key array:

/*
  Will trap key presses for an array of ascii keys
*/

int input[] = new int[2];
int keySelected;
boolean keyDwn = false;

void setup() {
  input[0] = 32;
  input[1] = 65;
}

void draw() {
  switch(keySelected) {
  case 32:
    if (keyDwn) {
      println("spacebar dwn.");
    } else {
      println("spacebar up.");
    }
    break;
  case 65:
    if (keyDwn) {
      println("key A down.");
    } else {
      println("key A up.");
    }
    break;
  }
}

void keyPressed() {
  for (int x = 0; x < input.length; x++) {
    if (input[x] == 32 || input[x] == 65) {
      keySelected = keyCode;
      keyDwn = true;
    }
  }
}

void keyReleased() {
  for (int x = 0; x < input.length; x++) {
    if (input[x] == 32 || input[x] == 65) {
      keySelected = keyCode;
      keyDwn = false;
    }
  }
}

apodidae
  • 1,988
  • 2
  • 5
  • 9