Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Game: Move character while key down

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.

like image 433
Alex O'Brien Avatar asked Mar 20 '23 07:03

Alex O'Brien


1 Answers

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;
    }
like image 137
Steven Martin Avatar answered Mar 29 '23 13:03

Steven Martin