我正在一个项目中,您可以在屏幕上控制角色。我使用的精灵表会根据您的行走方式来更改帧。当我按下向上箭头键并且动画可以工作时,我已经设置了它的工作位置,但是现在我很难弄清楚如何实现停止动画的逻辑。
在这里,我的移动箱子开关看起来像这样:
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()
答案 0 :(得分:1)
如果要在用户停止按某个键后调用函数,则需要添加一个 keyup 事件。就像您的 keydown 事件处理程序一样,您可以检查每个箭头键。希望以下示例对您有所帮助。
const game = document.getElementById('game');
document.addEventListener('keydown', event => {
event.preventDefault();
game.textContent = "keyDown: " + event.key;
});
document.addEventListener('keyup', event => {
event.preventDefault();
game.textContent = "keyUp: " + event.key;
});
<div id="game">Click on me, then press a key!</div>