Tuesday, May 14, 2024
 Popular · Latest · Hot · Upcoming
13
rated 0 times [  17] [ 4]  / answers: 1 / hits: 8283  / 10 Years ago, fri, march 7, 2014, 12:00:00

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.


More From » jquery

 Answers
3

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;
}

[#47063] Friday, March 7, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kristopher

Total Points: 58
Total Questions: 103
Total Answers: 102

Location: Netherlands
Member since Thu, Jul 1, 2021
3 Years ago
;