I am writing a game on processing. When you press the LEFT key, the hero shifts a couple of pixels, then waits for a split second and only then continues to move.

void keyPressed(){ if (keyCode == LEFT) hero.pozx -= hero.v0; } 

Same problem:

 void setup(){ size(200,200); } void draw(){ background(0,255,0); } void keyPressed(){ rect(100,100, 100, 100); } 
  • In this piece of code is quite difficult to find the problem. - michael_best
  • try somewhere to display the phrase "the hero has moved" - michael_best 6:49 pm
  • @michael_best I suspect that the problem is not in the error in the code, but in the wrong method, now I will add a small program-explanation - Maxim Faleev
  • And when you press the button to the left in the editor, does the cursor start moving without delay? - Oleksiy Morenets
  • @ OlexiyMorenets in the editor - yes, but in games - no - Maxim Faleev

1 answer 1

You bind the movement of the character directly to the keyboard event, as a result, you get the first short character shift after a single key press event occurs, then there is a delay until the key is defined as squeezed and the event is called again until the key is released. Try to move the character on a timer, and on the keyboard events, hang up only the changes in the flags of the pressed buttons. Example:

 boolean keyLeftPressed; onKeyDown() { if (keyCode == LEFT) keyLeftPressed = true; } onKeyUp() { if (keyCode == LEFT) keyLeftPressed = false; } onTimer() { if (keyLeftPressed) hero.pozx -= hero.v0; }