Javascript Game: moving a character when a key is pressed

I am making a simple canvas-based Javascript / HTML game for school. I have a character moving left or right at level 2. Initially, I simply added an event listener and in the switch, to determine which key was pressed, I would increase the location of the character by a certain number of pixels. This caused the movement to be very jerky and difficult to work.

What I want to do is a smooth movement when the key is pressed, stopping immediately after releasing it.

I thought that if there was some kind of "so far key" function, I could use that.

If this is the best way to do this, how can I do it, and if there is a better way, I would like to know.

NOTE. I would prefer not to use external libraries. I'm fine with jQuery, but I don't want to learn a whole new way to make my game.

+4
source share
1 answer

Perhaps you should consider adding acceleration to the variable, which increases when you hold the button down as the force increases, so that the players will move until they reach maximum speed, thus achieving an even feeling.

I added a sudden stop when you release left / right, but I would not recommend this, instead reduce xforce to 0 to have a smooth feeling that also slows down.

pixelx - , ( )

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;

...

    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;

...

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

Source: https://habr.com/ru/post/1530701/


All Articles