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 に答える