移动对象从左到右

时间:2014-12-30 15:52:40

标签: javascript jquery

在我的游戏中,我将添加从<div id="outline"></div>

左右移动的障碍物

我已经将setInterval(){...}.animate()一起使用了,它似乎只有问题是在离开ouline一段时间之后,下面是一些代码和链接。< / p>

$(document).ready(function() {
setInterval(function(){
      $("#CObject").animate({
    'marginLeft' : "+=220px" //moves left
    }, 900);
 }, 900);
setInterval(function(){
      $("#CObject").animate({
    'marginLeft' : "-=220px" //moves left
    }, 900);
 }, 1000);
});

Link.

4 个答案:

答案 0 :(得分:4)

更改为“ - = 220px”:

setInterval(function(){
    $("#CObject").animate({
      'marginLeft' : "-=220px" //moves left
    }, 900);
}, 900);

要匹配 900 时间间隔,它会偏移 100

答案 1 :(得分:3)

如果你想知道。还有另一种方法可以在不使用setInterval的情况下执行您想要的操作,在这种情况下,您必须等待动画结束才能启动反向动画。

$(document).ready(function() {
    animate(false);
});

function animate(reverse) {
    $("#CObject").animate({
        'marginLeft' : (reverse) ? "-=220px" : "+=220px" //moves left
     }, 900, function() {
       // Run when animation finishes
       animate(!reverse); 
    });
}

通过这种方式,您可以确保在开始任何其他操作之前完成动画

答案 2 :(得分:0)

没有setInterval:

$(document).ready(function() {

    function loop() {

        $("#CObject").animate({
            'marginLeft' : "+=220px" //moves left
        }, 900, 'linear', function() {
            loop();
        });

        $("#CObject").animate({
            'marginLeft' : "-=220px" //moves left
        }, 900, 'linear', function() {
            loop();
        });

    }

    loop();

});

fiddle

使用动画创建一个循环函数,然后在动画结束时调用它。

答案 3 :(得分:0)

为确保动画完成,我只需让每个方向动画在完成时调用另一个。如果查看animate的API,您将看到第四个参数是针对动画完成时将调用的函数。 http://api.jquery.com/animate/

$(document).ready(function() {
    animateRight();
});

function animateRight() {
    $("#CObject").animate({
        'marginLeft' : "+=220px" //moves left
    }, 900, 'swing', animateLeft);
}

function animateLeft() {
    $("#CObject").animate({
        'marginLeft' : "-=220px" //moves right
    }, 900, 'swing', animateRight);
}

这是小提琴:http://jsfiddle.net/cgdtfxxu/

相关问题