I'm making a simple canvas-based Javascript/HTML game for school. I have a character, moving left or right on a 2d level. Originally, I just added an event listener and in a switch to determine which key was pressed, I would increment the character's location by a certain number of pixels. This caused movement to be very jerky and difficult to work with.
What I want to happen is have smooth movement while the key is pressed, the stop immediately when it is released.
I was thinking that if there were some sort of "while key down" functionality, then I could use that.
If that is the best way to do this, how could I do that, and if there is a better way, I'd love to know it.
NOTE: I'd rather not have to use external libraries. I'm fine with jQuery, but I don't want to have to learn a whole new way to do my game.
You might need to consider adding acceleration to the variable that increase as you hold the button down, as the force increases, so will the players speed until a max speed is reached, this is how a smooth feel is achieved.
I have added the sudden stop when you let go left/right but i wouldnt advise this, instead reduce the xforce until 0 to have a smooth feel also slowing down.
pixelx is the distance you should move player per loop(game tick)
window.addEventListener('keydown', handleKeyDown, true)
window.addEventListener('keyup', handleKeyUp, true)
var maxspeed = 6;
var xforce = 0;
var pixelx = 0;
var direction = 1;
var key_left = false;
var key_right = false;
in game loop...
if (key_left)
{
xforce--;
direction = -1;
}
if (key_right)
{
xforce++;
direction = 1;
}
if (xforce > maxspeed)
xforce = maxspeed;
if (xforce < -maxspeed)
xforce = -maxspeed;
if (!key_left && !key_right)
{
pixelx = 0;
xforce = 0;
}
else
{
pixelx += xforce;
}
playerlocationx = playerlocationx + pixelx;
playerdirection = direction;
functions...
function handleKeyDown(event)
{
if (event.keyCode == 37)
key_left = true;
else if (event.keyCode == 39)
key_right = true;
}
function handleKeyUp(event)
{
if (event.keyCode == 37)
key_left = false;
else if (event.keyCode == 39)
key_right = false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With