我正在使用JQuery使用箭头键为div设置动画。
出于某种原因,当我重复箭头键按下当前方向时,动画每次都会慢慢减速。
我认为$player.stop()
和$player.clearQueue()
可以解决这个问题,但显然不是。有什么建议吗?
这里有一个jsfiddle:https://jsfiddle.net/qb484yp2/
我的JS代码如下。
$(document).ready(function () {
var $player = $('#player'),
$enemy1 = $('#enemy1'),
$bg = $('#container'),
playerW = $player.outerWidth(),
playerH = $player.outerHeight(),
bgW = $bg.width(),
bgH = $bg.height(),
playerX,
playerY,
enemySpeed = 1000,
playerSpeed = 1000,
direction,
down = false;
var targetSound1 = $('#targetSound1')[0];
targetSound1.loop = true;
function keypress(e) {
$player.clearQueue();
$player.stop()
if (down) {
return;
}
down = true;
var playerLeft = $player.css('left');
var playerTop = $player.css('top');
var key = e.which || e.keyCode;
if ([38, 40, 37, 39].includes(key)) {
e.preventDefault(); // prevent defualts (scrolling)!
}
if (key == "37") {
direction = 'left';
playerLeft = 0;
} else if (key == "38") {
direction = 'up';
playerTop = 0;
} else if (key == "39") {
direction = 'right';
playerLeft = bgW - playerW;
} else if (key == "40") {
direction = 'down';
playerTop = bgH - playerH;
}
$player.animate({
left: playerLeft,
top: playerTop
},
playerSpeed, 'linear');
}
function makeNewPosition($container) {
// Get viewport dimensions (remove the dimension of the div)
$container = ($container || $(window))
var h = $container.height() - 50;
var w = $container.width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
function animateDiv() {
var $target = $($enemy1);
var newq = makeNewPosition($target.parent());
var oldq = $target.offset();
var speed = enemySpeed;
$($enemy1).animate({
top: newq[0],
left: newq[1]
}, speed, 'linear', function () {
animateDiv();
});
};
$(document).on('keydown', keypress);
$(document).on('keyup', function () {
down = false
});
animateDiv();
});
答案 0 :(得分:1)
解决方案:所以我的逻辑是,如果触发事件的键是触发上一个事件的键,我们就不应该再为#player div制作动画了。只有当密钥发生变化时,我们才能为其设置动画。这将阻止不必要的动画堆积和减慢动画。所以我认为我们可以跟踪最后一个动画,只有按下的键已经改变,我们才会允许动画发生。结果:平滑动画:)
这是诀窍的代码!查看整个代码的小提琴
if(key==lastKey)
{
return;
}
else
lastKey=key;
此外,您必须从代码中删除此行,因为它会停止播放器div的动画。
$player.stop()