keyCode repeats forever


#1

float brush_x = 10;
float brush_y = 10;

void setup() {
size(800,800);
background(0);
rectMode(CENTER);
frameRate(300);
}

void draw() {
if(mousePressed == true) {
noStroke();
ellipse(mouseX,mouseY,brush_x,brush_y);
}
if(keyCode == DOWN) {
brush_x = brush_x - 1;
brush_y = brush_y - 1;
} else
if(keyCode == UP) {
brush_x = brush_x + 1;
brush_y = brush_y + 1;
}

}

This is my code and whenever I press the up/down arrow it adds 1 to the size every frame even if I release it it still keeps going. Does anyone know how to fix this?


#2

The keyCode variable holds the most recently pressed key, whether that key is still pressed or not. You might want to also check the keyPressed variable as well:

if(keyPressed){
 if(keyCode == DOWN) {
  brush_x = brush_x - 1;
  brush_y = brush_y - 1;
 } else
 else if(keyCode == UP) {
  brush_x = brush_x + 1;
  brush_y = brush_y + 1;
 }
}