I'm making a game with simple movement code. I don't want the movement to be too complex since it's going to be a small game once it's done.

Right now the character moves 10 units at a time, then stops, then 10 units, then stops, and this looks jerky.

I'd like the character to move continuously, without stopping in between. I tried lowering the playerSpeed to make it less jerky, but then the character moved too slowly and players got bored. Instead I want the character to move a little every frame, not a big jump with delays in between.

Here's what I've tried so far:

playerSpeed = 10;

document.addEventListener('keydown', function(e){
 if(e.key === 'w' && playerY >= 5){
  playerY-= playerSpeed;
  ctx.clearRect(0, 0, outerWidth, outerHeight);
 if(e.key == 'd' && playerX < outerWidth - 50){
  playerX+= playerSpeed;
  ctx.clearRect(0,0,outerWidth, outerHeight);

if(e.key == 's' && playerY < outerHeight - 100){
 playerY+= playerSpeed;
 ctx.clearRect(0,0,outerWidth, outerHeight);

if(e.key == 'a' && playerX > 5){
  playerX-= playerSpeed;
 ctx.clearRect(0, 0,outerWidth, outerHeight);
  • \$\begingroup\$ So what's wrong with increasing the movement speed? \$\endgroup\$ – Tyyppi_77 Sep 27 '16 at 12:19
  • 5
    \$\begingroup\$ I don't understand your question. You reduced movement speed, testers didn't like it, you changed it back. So what problem do you still have? You said you want "more natural" movement. What exactly do you mean with that? What makes the movement feel "unnatural"? There might be plenty of possible reasons for that. \$\endgroup\$ – Philipp Sep 27 '16 at 12:41
  • \$\begingroup\$ @Phillip I mean, when you move in the game, u move 10 pixels at at time. Is there anyway to make it so u move 1 pixel at a time but faster? \$\endgroup\$ – The Gamer King Sep 27 '16 at 19:39
  • \$\begingroup\$ "Is there anyway to make it so u move 1 pixel at a time but faster?" Zoom out? Maybe adding an animated gif (use something like screentogif or gifcam) could help show the behaviour you'd like to improve. \$\endgroup\$ – Vaillancourt Sep 27 '16 at 20:42

The movement isn't smooth because you only move your character when the keydown event is emitted which occurs at most a few times per second (I'm not sure how often exactly).

What you want to do instead is, have a boolean variable which tells you whether a key has been pressed (set to true on keydown, false on keyup). In your main game loop, if the variable is set to on, you would then move the player by playerSpeed * timeDelta (difference in time between now and the previous iteration, which you can calculate using getTime).

  • \$\begingroup\$ Ok, could you put that in code plz? \$\endgroup\$ – The Gamer King Sep 27 '16 at 20:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.