I am trying to set up little game in Canvas with Html and JS. I encounter one problem and I don't understant what am I missing.
I draw two sprites sheets in the canvas, but when they arrives near each other, the one on the bottom of my drawloop erase the other one.
I import my srpites, draw and animate them and call everything in a drawloop with a setTimeout to reduce the speed of the animations
function drawArthur() {
updateFrame();
animations();
resetAnimations();
context.drawImage(arthurImage, arthur.srcX, arthur.srcY, arthur.width, arthur.height, arthur.x, arthur.y, arthur.width, arthur.height);
arthurImage.style.zIndex = '1';
}
function updateFrame() {
arthur.currentFrame = ++arthur.currentFrame % arthur.colums;
arthur.srcX = arthur.currentFrame * arthur.width;
arthur.srcY = 0;
context.clearRect(arthur.x, arthur.y, arthur.width, arthur.height);
// if (myModule.newZombie.isCrashed) {
// arthur.die = true;
// console.log(arthur.die);
// }
}
function animations() {
arthur.srcX = arthur.currentFrame * arthur.width;
if (arthur.goRight) {
arthur.srcY = arthur.goRowRight * arthur.height;
} else if (arthur.goLeft) {
arthur.srcY = arthur.goRowLeft * arthur.height;
} else if (arthur.duckRight) {
arthur.srcY = arthur.duckRowRight * arthur.height;
} else if (arthur.atkRight) {
arthur.srcY = arthur.atkRowRight * arthur.height;
if (zombie.x < 274 && zombie.x > 262) {
console.log('killllll');
zombie.dieRight = true;
} else if (zombie.x < 262) {
zombie.dieRight = false;
zombie.x = -50;
} else if (arthur.jumpRight) {
arthur.srcY = arthur.jumpRowRight * arthur.height;
}
}
}
// function that reset all states every time in the draw loop to set the states at the origin state
function resetAnimations() {
arthur.stand = arthur.right;
arthur.goLeft = false;
arthur.goRight = false;
arthur.duckRight = false;
arthur.atkRight = false;
arthur.jumpRight = false;
}
function drawLoop() {
setTimeout(function () {
context.clearRect(0, 0, theCanvas.width, theCanvas.height);
drawArthur();
drawZombie();
requestAnimationFrame(function () {
drawLoop();
});
}, 150);
createNewZombie();
console.log(allZombies);
}
I cant manage two get my two characters, to just overlap each other. The last one in the drawloop, here the Zombie, will erase Arthur when he passes over him.
Thanks !
Assuming that your drawZombie
methods also calls a similar updateFrame()
method,
and that it also has a line like context.clearRect(arthur.x, arthur.y, arthur.width, arthur.height);
What's happening is that you
1) clear the area behind Arthur
2) draw Arthur
3) clear the area behind Zombie(s) even if Arthur is behind the Zombie
4) draw the Zombie(s)
Because you're clearing the entire canvas in drawLoop
with context.clearRect(0, 0, theCanvas.width, theCanvas.height);
you don't need to then do (1) & (3).
Remove the context.clearRect(...)
from the updateFrame
methods.
or
If you do want to have those extra clearRect(...)
just make sure that they all happen before you draw Arthur and the Zombie(s)
Hope this helps