0

When I press down the right and left arrow keys, instead of moving left and right as expected, the character jerks forward, stops, and restarts, all while I have the button pressed down.

I have the whole game up here: https://codepen.io/alexis-lee-ann-stockdale/pen/qzvrop

I think the problem is somewhere in the update function or in the keys function.

Here is was I've written in the update function to move the character:

    game.player.y += game.player.vely;
    game.player.posx += game.player.velx;
    game.player.velx *= game.world.friction;
    game.player.vely += game.world.gravity;

If this is too invovled a question to answer, could you please point me to a tutoring service that I could perhaps use? Thank you in advance.

  • Is there a specific reason for multiplying by the friction? Instead of subtracting or something? – Caleb H. Jul 11 '19 at 16:36
  • I was following a tutorial that multiplied by the friction. It was for a static 2d game, and not a side scroller. It's here: https://www.youtube.com/watch?v=w-OKdSHRlfA Would subtracting make it smooth? I'm brand new to game developement. – Alexis Lee Ann Stockdale Jul 11 '19 at 16:40
  • I tried that just now. It made the character slide to the right automatically. – Alexis Lee Ann Stockdale Jul 11 '19 at 16:42
  • I didn't look very far into how your code works, so I don't really know. Really, friction is a force that you would subtract from the force ( mass * acceleration ) of your character, which would affect the velocity indirectly. – Caleb H. Jul 11 '19 at 22:53

1 Answers1

1

As far as I can tell, the reason for the stop and restart behavior is key repetition. You're listening to the keydown event, and this is triggered once when the key is pressed, and then again each time the OS repeats the key as it is held.

What you need to do is move right or left as long as the key is pressed. You'll need to keep track of when a key is pressed and released, unfortunately there's not an easier way.

joshwilsonvu
  • 2,569
  • 9
  • 20