防止关键事件延迟

时间:2016-03-14 10:14:54

标签: javascript createjs

我正在使用createjs。我的目标是在其中一个WASD键按下一个条件时移动纹理,纹理只能在一个方向上移动一次。这是我的代码的相关部分:

//I use this to prevent simultaneous key events
var currentKeyCode = null; 

//Assign event listener
window.addEventListener("keydown", handleMovement, false); 
window.addEventListener("keyup", setMovementFlag, false);


//This will make the hero move 
//only if no other key is down or if it is the same key as in last event
function handleMovement(event) {
    if (!currentKeyCode || currentKeyCode == event.keyCode) {
        currentKeyCode = event.keyCode;
        hero.Move(event);
    }
}

//Here the keyCode flag is set to null as no key is currently being pressed
function setMovementFlag(event) {
    currentKeyCode = null;
}

//And finally this is the code that moves the "texture" based on the event
Hero.prototype.Move = function (event) {
    switch (event.keyCode) {
        case 65: // A down, move left
            var nextPositionX = this.texture.x - this.speed;

            this.facingDirection = 'left';

            if (!this.PredictCollision(new Vector2(nextPositionX, this.texture.y))) {
                this.texture.x -= this.speed;
            }
            break;
        case 68: // D down, move right
            var nextPositionX = this.texture.x + this.speed;

            this.facingDirection = 'right';

            if (!this.PredictCollision(new Vector2(nextPositionX, this.texture.y))) {
                this.texture.x += this.speed;
            }
            break;
        case 83: //S down, move down
            var nextPositionY = this.texture.y + this.speed;

            this.facingDirection = 'down';

            if (!this.PredictCollision(new Vector2(this.texture.x, nextPositionY))) {
                this.texture.y += this.speed;
            }
            break;
        case 87: //W down, move up
            var nextPositionY = this.texture.y - this.speed;

            this.facingDirection = 'up';

            if (!this.PredictCollision(new Vector2(this.texture.x, nextPositionY))) {
                this.texture.y -= this.speed;
            }
            break;
        default:
    }
}

问题是每当我按住一个键时纹理会移动一点,然后它似乎会冻结片刻直到它继续前进。 我不确定问题是在我的实现中,还是在JavaScript中如何处理事件。但是这种行为使得运动以某种方式出现了口吃。

0 个答案:

没有答案