从左到右移动对象

Moving object Left To Right

本文关键字:对象 移动 从左到右      更新时间:2023-09-26

在我的游戏中,我将添加障碍物,这些障碍物在<div id="outline"></div>上从左到右移动

我已经将setInterval(){...}与其中的.animate()一起使用,它似乎有效,唯一的问题是在一段时间后它离开了线路,下面是一些代码和一个链接。

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

链接。

在"-=220px"上更改为:

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

为了匹配 900 时间间隔,它偏移量为 100

如果你想知道的话。还有另一种方法可以在不使用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); 
    });
}

这样,您可以确保动画将在开始其他任何内容之前完成

Without 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();
});

小提琴

使用动画创建一个循环函数,然后在动画完成后调用它。

为了确保动画完成,我只会让每个方向的动画在完成时调用另一个。如果您查看 API for animate ,您将看到第四个参数用于动画完成后将调用的函数。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/