I have a situation where I am using JQuery to create animation effects on a div element based on arrow key inputs.
However, I am encountering an issue where the animation slows down significantly each time I repeat pressing the arrow key for the current direction.
I tried using $player.stop()
and $player.clearQueue()
functions to resolve this problem, but they did not work as expected. Any suggestions on how to fix this?
You can access the JSFiddle demonstration of the issue here: https://jsfiddle.net/qb484yp2/
Below is the JavaScript code snippet I am currently using:
$(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();
});