I have a Pacman clone originally built with HTML5/CSS3/JQuery. I am trying to change the Pacman character (which was originally coded with a canvas arc method) to a custom animated character using requestAnimationFrame and a spritesheet. I was able to create the spritesheet and animate it without issue, then I was able to bind it to the variables that allow Pacman to move. However the strange issue I am noticing is that Pacman is only animated when he hits a wall or when the game is paused (hitting the ‘P’ key) or when he dies. Also note that I only mapped the spritesheet canvas for when Pacman goes right
(PACMAN_DIRECTION === 1)
All other directions are mapped to a static image file (I plan to update the rest later on). The code in question:
function animateRight() {
var canvas = document.querySelector("#animation-canvas");
var context = canvas.getContext("2d");
var myImage = new Image();
myImage.src = "https://i.ibb.co/ydGKpCR/spritesheet3.png";
myImage.addEventListener("load", loadImage, false);
var shift = 0;
var frameWidth = 33;
var frameHeight = 29;
var totalFrames = 3;
var currentFrame = 0;
function loadImage(e) {
animate();
}
function animate() {
requestAnimationFrame(animate);
context.clearRect(0, 0, 33, 29);
context.drawImage(myImage, shift, 0, frameWidth, frameHeight, 0, 0, frameWidth, frameHeight);
shift += frameWidth + 1;
/*
Start at the beginning once you've reached the
end of your sprite!
*/
if (currentFrame == totalFrames) {
shift = 0;
currentFrame = 0;
}
currentFrame++;
}
}
function positionCanvas(canvasId, x, y) {
const position = document.getElementById(canvasId)
var ctx = getPacmanCanevasContext();
position.style.display = "block";
position.style.left = x + "px";
position.style.top = y + "px";
animateRight();
}
function drawPacman() {
var ctx = getPacmanCanevasContext();
ctx.beginPath();
if (PACMAN_DIRECTION === 1) {
positionCanvas("animation-canvas", PACMAN_POSITION_X - (PACMAN_SIZE / 2), PACMAN_POSITION_Y - (PACMAN_SIZE / 2));
} else if (PACMAN_DIRECTION === 2) {
img = document.getElementById("pacmandown"); //down
ctx.drawImage(img, PACMAN_POSITION_X - (PACMAN_SIZE / 2), PACMAN_POSITION_Y - (PACMAN_SIZE / 2), PACMAN_SIZE, PACMAN_SIZE);
} else if (PACMAN_DIRECTION === 3 ) { //left & up
img = document.getElementById("pacmanleft");
ctx.drawImage(img, PACMAN_POSITION_X - (PACMAN_SIZE / 2), PACMAN_POSITION_Y - (PACMAN_SIZE / 2), PACMAN_SIZE, PACMAN_SIZE);
} else {
img = document.getElementById("pacmanup");
ctx.drawImage(img, PACMAN_POSITION_X - (PACMAN_SIZE / 2), PACMAN_POSITION_Y - (PACMAN_SIZE / 2), PACMAN_SIZE, PACMAN_SIZE);
}
//ctx.arc(PACMAN_POSITION_X, PACMAN_POSITION_Y, PACMAN_SIZE, startAngle, endAngle, false);
//ctx.lineTo(lineToX, lineToY);
//ctx.fill();
ctx.closePath();
}
I don’t believe any other functions in the game files could be causing the issue, as I left them as-is for the most part. I also uploaded the game online so it can be tested: