1

我正在玩 Canvas,我的小家伙在画布上的“动画”出现问题,当我按住左键时,他应该在页面上飞驰时播放他的小动画,但是按住按钮时超时正在堆叠,所以他的动画变得很糟糕。我怎么可能控制他,setTimeouts让他看起来不那么该死的傻,谢谢!

运动相关代码:

   var playerMove = function(direction) {

        if (direction === 'left') {
            updatePlayer(0, 130, 100, 100, 100, 100, 100);
            setTimeout(function() {
                updatePlayer(100, 130, 100, 100, 100, 100);
            }, 100);
            setTimeout(function() {
                updatePlayer(180, 130, 100, 100, 100, 100);
            }, 200);
            setTimeout(function() {
                updatePlayer(100, 130, 100, 100, 100, 100);
            }, 500);
            setTimeout(function() {
                updatePlayer(0, 130, 100, 100, 100, 100, 100);
            }, 650);
        } else if (direction === 'right') {
                updatePlayer(0, 230, 100, 100, 100, 100, 100);
            setTimeout(function() {
                updatePlayer(100, 230, 100, 100, 100, 100);
            }, 100);
            setTimeout(function() {
                updatePlayer(180, 230, 100, 100, 100, 100);
            }, 200);
            setTimeout(function() {
                updatePlayer(100, 230, 100, 100, 100, 100);
            }, 500);
            setTimeout(function() {
                updatePlayer(0, 230, 100, 100, 100, 100, 100);
            }, 650);
        }
    };

               function movePlayer(e) {
            if (e.which === 37) {
                active = true;
                playerMove('left');
                player.destX -= 2;
            } else if (e.which === 39) {
                active = true;
                playerMove('right');
                player.destX += 2;
            }
    }

    document.addEventListener('keydown', function(e) {
            movePlayer(e);
    });

演示 源代码

4

2 回答 2

0

将您的超时存储在一个变量中,并在每次移动时使用 clearTimeout。在这种情况下,更好的用法是使用单个间隔,并清除 keyup 事件的间隔。

[编辑]

以间隔和玩家动作为例,只需要控制动画时间。

var playerMovementInterval = null;

function movePlayerLeft () {
     var actions = [
         [0, 130, 100, 100, 100, 100, 100],
         [100, 130, 100, 100, 100, 100],
         [180, 130, 100, 100, 100, 100],
         [100, 130, 100, 100, 100, 100],
         [0, 130, 100, 100, 100, 100, 100]
     ];

    var index = 0;
    clearInterval(playerMovementInterval);
    playerMovementInterval = setInterval(function() {
        updatePlayer.apply(window, actions[index]);
        index++;
        if (index > actions.length-1) clearInterval(playerMovementInterval);
    }, 200);                
}

var playerMove = function(direction) {

    if (direction === 'left') {
        movePlayerLeft();
    } else if (direction === 'right') {
.....
于 2013-04-27T22:22:15.043 回答
0

您可以在上次超时时将 active 设置为 false,并且仅在 !active... 时才调用 move()

于 2013-04-27T22:25:09.053 回答