I'm trying to animate a sprite sheet. I have a single image, and multiple objects of the same type but drawn at different locations on the canvas. What i'm trying to do is having each object with an animate speed of its own, and an overall game framerate using requestAnimationFrame, but it clears the whole canvas, instead of redrawing.
I've previously tried the setInterval approach, but it causes flickering (I can't really tell why, even I've googled it online.
const objectsArray = []
const gameFrameRate = 1000/30;
let allowedSoldiersQuantity = 30;
let globalImageObjects = [];
let newObject = new genericObject('robot.png', 200, 200);
objectsArray.push(newObject)
let otherObject = new genericObject('2.png', 300, 300);
objectsArray.push(otherObject)
canvas = document.getElementById('game_canvas');
context = canvas.getContext('2d');
canvas.width = 1200;
canvas.height = 720;
canvas.style.borderColor = 'red'
canvas.style.borderWidth = '5px'
setup = function() {
// setInterval Approach
//setInterval(function (){
// context.clearRect(0, 0, canvas.width, canvas.height)
// objectsArray.map((element) => {
// element.animateObjectImage(element.objectImage, 4)
// })
//},30)
// RequestAnimationFrame approach
objectsArray.map((element) => {
element.animateObjectImage(element.objectImage, 9)
})
context.clearRect(0, 0, canvas.width, canvas.height)
window.requestAnimationFrame(setup)
}
window.requestAnimationFrame(setup)
document.addEventListener('click', (event) => {
console.log(event.x);
console.log(event.y);
if (allowedSoldiersQuantity){
let object = new genericObject('robot.png', event.x, event.y)
objectsArray.push(object)
object.animateObjectImage(object.objectImage, 5)
allowedSoldiersQuantity -= 1;
}
}, false)
function genericObject(objectSpriteSheet, xPosition, yPosition){
this.objectImage = (function (){
let newImageObject = new Image()
newImageObject.src = objectSpriteSheet
return (newImageObject)
})()
this.animateObjectImage = function(objectImage, frameRate){
let setIntervalTime = 1000 / frameRate;
let currentFrame = 1;
let totalSprites = 8;
let spriteHeight = objectImage.height;
let spriteWidth = objectImage.width / totalSprites;
setInterval(function animateObjectSprites(){
currentFrame = (currentFrame + 1) % totalSprites;
let screenX = currentFrame * spriteWidth;
context.drawImage(objectImage, screenX, 0, spriteWidth, spriteHeight, xPosition, yPosition, spriteWidth, spriteHeight);
currentFrame++;
}, setIntervalTime)
}
}
//setup(); // This function should be run with the setInterval approach
```