We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpPrograms › MultipleKeypress: one solution
Page Index Toggle Pages: 1
MultipleKeypress: one solution (Read 782 times)
MultipleKeypress: one solution
Oct 10th, 2009, 4:25pm
 
A frequent problem is the overriding of key input by the most recent keypress.  This is a solution using a boolean for each key, flagged 'true' when pressed and 'false' when released.  It's important to keep this in "void keyPressed" rather than an "if (keyPressed)" statement in draw().  It will be much more responsive this way -- if it is in draw() it will miss keypresses depending on the current framerate.

boolean up, down, left, right;

void keyPressed(){
 switch(keyCode){
   case(LEFT):
   left = true;
   break;
   case(RIGHT):
   right = true;
   break;
 }
}

void keyReleased(){
 switch(keyCode){
   case(LEFT):
   left = false;
   break;
   case(RIGHT):
   right = false;
   break;
 }
}

void draw(){
 checkKeys();
}

void checkKeys(){
 if (left)... // move left
 if (right)... // move right
}

--Ben
Re: MultipleKeypress: one solution
Reply #1 - Oct 23rd, 2009, 12:04pm
 
This example moves a circle around, leaving a trail:
Quote:
boolean leftPressed, rightPressed, upPressed, downPressed;
float ellipseX, ellipseY;

void setup(){
 size(300,300);
 ellipseX = width/2;
 ellipseY = height/2;
 stroke(150);
 fill(0);
}

void draw(){
 checkKeys();
 ellipse (ellipseX, ellipseY, 20, 20);
}

void checkKeys(){
 if (leftPressed) ellipseX--;
 if (rightPressed) ellipseX++;
 if (upPressed) ellipseY--;
 if (downPressed) ellipseY++;
}

void keyPressed(){
 switch(keyCode){
   case(LEFT):
   leftPressed = true;
   break;
   case(RIGHT):
   rightPressed = true;
   break;
   case(UP):
   upPressed = true;
   break;
   case(DOWN):
   downPressed = true;
   break;
 }
}

void keyReleased(){
 switch(keyCode){
   case(LEFT):
   leftPressed = false;
   break;
   case(RIGHT):
   rightPressed = false;
   break;
   case(UP):
   upPressed = false;
   break;
   case(DOWN):
   downPressed = false;
   break;
 }
}
Page Index Toggle Pages: 1