从左到右移动对象
Moving object Left To Right
在我的游戏中,我将添加障碍物,这些障碍物在<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/
相关文章:
- FabricJs-限制主对象内添加对象的移动区域
- 在javascript中移动对象内部的元素
- 计算从一个对象到另一个对象的路径并沿其移动
- 如何在鼠标悬停时将对象从起始位置移动到结束位置,然后在鼠标悬停后再次移动
- 如何移动PIXI显示对象
- 使用Keydown事件移动对象
- 用鼠标在threejs场景中移动对象
- 如何将嵌套对象移动到外部对象
- JQuery 可拖动 - 防止网格对象移动到同一位置
- 在使对象移动时处理多次单击
- 如何将可拖动对象移动到某个区域
- 如何将另一个 JSON 中的 JSON 对象移动到最后一个位置
- 如何将值从 JSON 对象移动到 JS 数组
- 无法使对象移动.Javascript
- FabricJS:对象:移动事件不会在用户选择多个对象时触发
- 屏幕对象移动与滚动移动/客户端 X
- 画布上的图像块画布对象移动
- 如何将一个项目从JSON对象移动到另一个JSON对象
- js将一个对象移动到另一个对象的下面
- 如何使用AngularFire将对象移动到数组的顶部