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 & HelpSyntax Questions › slowing down keyboard input
Page Index Toggle Pages: 1
slowing down keyboard input (Read 192 times)
slowing down keyboard input
Jun 7th, 2009, 2:47am
 
I am not sure how I should approach this problem.

I am trying to slow they keyboard input. Basically I have a rectangle that that moves between 3 slots or lanes (top middle and lane).

The problem is the input is so fast that I can't keep my rectangle in the middle. If I press down (or 's' on my code) it will go to the bottom so fast.

Here is the part of code I am having problems with:
Code:
if(keyPressed)
{
if (key =='w' && laneNum > 1)
laneNum = laneNum - 1;
if (key =='s' && laneNum < 3)
laneNum = laneNum +1 ;
}
switch(laneNum)
{
case 1: //car on the top lane
kazX=0;
kazY=0;
break;

case 2: //car on the middle lane
kazX=0;
kazY=120;
break;

case 3: //car on the bottom lane
kazX=0;
kazY=250;
break;
}
rect(kazX,kazY,100,100);


Thank you Cheesy
Re: slowing down keyboard input
Reply #1 - Jun 7th, 2009, 10:36am
 
One simple solution is to use a counter to check how long the key has been held down:

Code:
int laneNum = 3;
int hitCounter = 0;
int hitDelay = 90;

void setup() {
   
}

void draw() {
 if(keyPressed) {
   if (key =='w' && laneNum > 1 && hitCounter <= 0) {
       laneNum = laneNum - 1;
       hitCounter = hitDelay;
       println(laneNum);
   }
   else {
     hitCounter --;  
   }

   if (key =='s' && laneNum < 3 && hitCounter <= 0) {
       laneNum = laneNum +1 ;
       hitCounter = hitDelay;
       println(laneNum);
   }
   else {
       hitCounter --;
   }
 }
}

void keyReleased() {
   hitCounter = 0;
}


This approach means a quick tap and release is registered as a hit (and this applies to subsequent taps because hitCounter is set to 0 when the key is released).  If you press and hold the key, hitCounter is set to hitDelay (adjust this value to determine the pause between hits - higher numbers equal longer pauses) and reduced by 1 each frame until it reaches 0 and a hit is registered.

If you want to allow multiple keypresses (e.g. you want the user to be able to move left and right as well as up and down all at the same time), you may want to look at this thread to see how best to handle multiple keypresses, though in this case you may need to create a separate counter for each key to deal with what happens when a key is released...
Page Index Toggle Pages: 1