【发布时间】:2019-07-11 06:05:11
【问题描述】:
我正在开发一个项目,您可以在其中控制屏幕周围的角色。我正在使用一个精灵表,它会根据你走路的方式改变框架。当我按下向上箭头键并且动画工作时,我已经将它设置在它工作的位置,但现在我无法弄清楚如何实现停止动画的逻辑。
这是我的移动案例开关的样子:
switch (e.which) {
case 38: //up
console.log("Up")
$(".player").finish().animate({
top: "-=10"
}, 100);
animateScript();
checkCollisions();
//if collision is detected, bounce back
if (colliding) {
$(".player").finish().animate({
top: "+=20"
}, 100);
}
break;
case 37: //left
console.log("Left")
$(".player").finish().animate({
left: "-=10"
}, 100);
checkCollisions();
//if collision is detected, bounce back
if (colliding) {
$(".player").finish().animate({
left: "+=20"
}, 100);
}
break;
case 39: //right
console.log("Right")
$(".player").finish().animate({
left: "+=10"
}, 100);
checkCollisions();
//if collision is detected, bounce back
if (colliding) {
$(".player").finish().animate({
left: "-=20"
}, 100);
}
break;
case 40: //down
console.log("Down")
$(".player").finish().animate({
top: "+=10"
}, 100);
checkCollisions();
//if collision is detected, bounce back
if (colliding) {
$(".player").finish().animate({
top: "-=20"
}, 100);
}
}
我只在第一种情况下实现了 animateScript() 并且它有效。现在我不知道如何实现我的 stopAnimation() 函数,也不知道在哪里。基本上,必须在用户停止使用箭头键时触发它。有什么想法吗?
动画函数如下:
var tID; //clear the setInterval()
function stopAnimate() {
clearInterval(tID);
}
//end of stopAnimate()
function animateScript() {
var position = 50; //start position for the image slicer
const interval = 100; //100 ms of interval for the setInterval()
const diff = 50; //diff as a variable for position offset
tID = setInterval ( () => {
$('.player').css('background-position', `-${position}px 0px`);
//we use the ES6 template literal to insert the variable "position"
if (position < 1601)
{ position = position +
diff;}
//we increment the position by 50 each time
else
{ position = 50; }
//reset the position to 50px, once position exceeds 1536px
}
, interval ); //end of setInterval
} //end of animateScript()
【问题讨论】:
-
animateScript()和stopAnimation()中有什么内容? -
刚刚用代码编辑了帖子,对不起
标签: javascript jquery animation sprite