Задержка при передвижении персонажа
При передвижении персонажа происходит некая задержка. Как пример, зажимаю клавишу управления, персонаж двигается только на несколько координат, через некоторое время двигается так, как мне необходимо.
Не подскажете, как убрать данную проблему?
const canv = document.querySelector("canvas");
let ctx = canv.getContext("2d");
canv.height = 768;
canv.width = 1024;
class Unit {
constructor(options) {
this.ctx = options.ctx;
this.image = options.image;
this.width = options.width;
this.height = options.height;
this.cordinateFrameY = 580;
this.numberOfFrames = options.numberOfFrames;
this.lengthFrames = (this.numberOfFrames * this.width) - this.width;
this.positionX = options.position.x;
this.positionY = options.position.y;
this.velocity = options.velocity;
this.tick_count = 0;
this.x = 0;
this.tick();
}
tick() {
if (this.tick_count > 5) {
this.draw();
this.tick_count = 0;
}
this.tick_count += 1;
requestAnimationFrame(() => {
this.tick();
});
}
draw() {
this.x = (this.x === this.lengthFrames ? this.width : this.x + this.width);
ctx.clearRect(0, 0, canv.width, canv.height);
ctx.drawImage(this.image, this.x, this.cordinateFrameY, this.width, this.height, this.positionX, this.positionY, this.width, this.height);
}
moveLeft() {
this.positionX -= this.velocity;
this.cordinateFrameY = 580;
}
moveRight() {
this.positionX += this.velocity;
this.cordinateFrameY = 708;
}
moveTop() {
this.positionY -= this.velocity;
this.cordinateFrameY = 516;
}
moveDown() {
this.positionY += this.velocity;
this.cordinateFrameY = 644;
}
}
let knightSprite = new Image();
knightSprite.src = 'assets/knight_unit.png';
knightSprite.onload = function () {
let knight = new Unit({
height: 64,
width: 64,
ctx: canv.getContext("2d"),
image: knightSprite,
numberOfFrames: 9,
position: {
x: 0,
y: 0
},
velocity: 2
})
function animate() {
window.addEventListener('keydown', function (event) {
switch (event.key) {
case 'ArrowUp':
knight.moveTop();
break;
case 'ArrowDown':
knight.moveDown();;
break;
case 'ArrowLeft':
knight.moveLeft();
break;
case 'ArrowRight':
knight.moveRight();
break;
}
});
}
animate();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Animation</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script src="custom.js"></script>
</body>
</html>
Источник: Stack Overflow на русском