Smooth Key Events

Hello.

I am haveing trouble with doing my controls right for my game. The problem is that it is more of a logical error and I can not get it to work smoothly. Like when i push and hold on the up arrow, it will go up then stop for like half a seconed then continue going up. I am using keyEvents and do it like most tutorials show on the web, but this seems to not work well for me. I want it to go up and keep going up when i hold down my key and not stop for like half a seconed then continue normaly. I am not sure what I am doing wrong. I looked on the web for tutorials, but most of them are just the old keyUP and keyDown ones.

public void keyPressed(KeyEvent e){
int codeNum= e.getKeyCode();

if (codeNum==e.VK_UP){

if (ya>0)
ya=ya-8;
ballDir=‘u’;

repaint();
}else if (codeNum==e.VK_DOWN){

if (ya<178)
ya=ya+8;
ballDir=‘d’;

repaint();
}//End IF

}//END METHOD

public void keyTyped(KeyEvent e){
int codeNum= e.getKeyCode();

}//END METHOD

public void keyReleased(KeyEvent e){
int codeNum=e.getKeyCode();
}//END METHOD

You’re doing it wrong.

On key down… set the flag to true (or 1)… on key up… set the flag to false (or 0).

In your main loop you just react accordingly to the values of those flags.


public class WhatSoEver implements KeyListener
{
static int [] controls = new int[256];
[...]
if(controls[KeyEvent.VK_LEFT]==1)
//do something
[...]
public void keyPressed(KeyEvent ke)
{
      controls[ke.getKeyCode()&0xff] = 1;
}
public void keyReleased(KeyEvent ke)
{
      controls[ke.getKeyCode()&0xff] = 0;
}
public void keyTyped(KeyEvent ke){}

That’s it.

in case why you’re wondering why you have to do it this way… it’s because of the system’s keyboard-repeat setting. You’ll notice the same delay for any key you press in, say, a word processing program. If there was no delay, you might hold the space key for half a second and end up with 10 spaces :stuck_out_tongue:

the KeyEvent events are fired as fast as the keyboard-repeat rate is set to. So the boolean flag might keep getting set to the same value several times, but like oNyx is saying, you can check the flag in your loop any time you want.