質問

So I am at the very beginning stages of creating my first platform style game in html5.So far I have only implemented left and right movement and no 'gravity' or collision detection is at play.

However, I've already hit an issue.

If you go left or right for a short period of time the 'character' acts as intended (I use character loosely as it's the map that is actually moving). If, however, you hold the key down the map moves too fast.

I figure the issue is that the keydown event listener is listening all of the time, there for moving the map is moving before each tick or frame of the game.

So my question is how can I make the keydown increase the map offset only on every tick of the game (20 milliseconds).

Here is my JSFiddle: CLICK HERE

document.addEventListener('keydown',function(event){
    var dir = event.which;

    if(dir == directions.LEFT){
        mapOffsetX += mapOffsetDistanceX;
        event.preventDefault();
    };

    if(dir == directions.RIGHT){
        mapOffsetX -= mapOffsetDistanceX;
        event.preventDefault();
    };
});

document.addEventListener('keyup',function(event){
    var dir = event.which;

    if(dir == directions.LEFT){
        mapOffsetX -= mapOffsetDistanceX;
    };

    if(dir == directions.RIGHT){
        mapOffsetX += mapOffsetDistanceX;
    };
});

initFloorObject(100,c.height/2,300,20,0,0,0,1);

var myInt = setInterval(function(){

clearScreen();

for(var i=0;i<floorObject.length;i++){
    floorObject[i][0] = parseInt(floorObject[i][0])+mapOffsetX;
};

drawChar();
drawFloorObjects();

},20);
役に立ちましたか?

解決

Set variable to false every time you keydown and set it back to true every 20 milliseconds.

var isKeydownAvailable = true;
document.addEventListener('keydown', function (event) {
    var dir = event.which;
    if(isKeydownAvailable){
        if (dir == directions.LEFT) {
            mapOffsetX += mapOffsetDistanceX;
            event.preventDefault();
        };

        if (dir == directions.RIGHT) {
            mapOffsetX -= mapOffsetDistanceX;
            event.preventDefault();
        };
        isKeydownAvailable = false;
    };
});

In the interval, reset the isKeydownAvailable to true.

var myInt = setInterval(function () {

    clearScreen();

    for (var i = 0; i < floorObject.length; i++) {
        floorObject[i][0] = parseInt(floorObject[i][0]) + mapOffsetX;
    };

    drawChar();
    drawFloorObjects();
    isKeydownAvailable = true;

}, 20);

他のヒント

Use booleans for actions and check for them inside your interval.
On keydown you set the boolean isMovingLeft to true, then you add the offset in your interval function only if(isMovingLeft). Do that for the other actions and you are good to go.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top