The sketch crashes when I press some other key that isn't a letter or a number

If I press a key like shift, alt, caps lock, etc. the sketch crashes. How do I make this stop happening? Thanks for reading this :slight_smile: here’s the code:

float v = 5;
int x = 1920/2;
int y = 1080/2;
boolean [] keys = new boolean[128];

import java.awt.Robot;

Robot robot;

void setup () {
  size(600, 600);
  try {
    robot = new Robot();
  } 
  catch (Throwable e) {
  }
}

void draw() {
  if (keyPressed) {
    if (keys['w']) {
      y -= v;
    }

    if (keys['a']) {
      x -= v;
    }

    if (keys['s']) {
      y += v;
    }

    if (keys['d']) {
      x += v;
    }  
  }
  robot.mouseMove(x, y);
}

void keyPressed() {
  keys[key] = true;
}

void keyReleased() {
  keys[key] = false;
}
1 Like

You could pick a higher value than 128:
Studio.ProcessingTogether.com/sp/pad/export/ro.9cfU11egvzT6G

3 Likes

Hello,

Try this:

boolean [] keys = new boolean[128];

void setup() {
}

void draw() {
}

void keyPressed() {
  println(key, int(key));
  if(key<128)
    keys[key] = true;
}

void keyReleased() {
  println(key, int(key));
  if (key<128) 
    keys[key] = false;
}

I added some println() statements to help you understand what is happening

:)

1 Like

thanks that’s it! Sorry for late response, I just didn’t continue what I was doing, but now that I searched about the same problem I saw my question and then your awnser, and it also worked for that different situation! thanks!

2 Likes