I ran into an issue when using addEventListener inside of array. My goal is to reduce "enemy" hp after each click. Adding a bit of code for explanation:
var image;
var enemy = [];
function start()
{
image = document.getElementById("image");
enemy.push(new createEnemy());
draw()
}
function draw()
{
if(enemy[0].hp <= 0) enemy.splice(0 , 1); /*Also, will my splice work
if instead of enemy[0] a "for loop" with (if(enemy[i].hp <= 0) enemy.splice(i, 1);)
was used?*/
requestAnimationFrame(draw);
}
function createEnemy()
{
this.hp = 2; //Value to be decreased
this.image = document.getElementById("image");
this.image.addEventListener("click", function()
{
console.log("Click works but hp doesn't decrease");
this.hp--; //Problem cause
})
}
<!DOCTYPE html>
<html>
<body onload="start()">
<img id="image" src="https://i.imgur.com/hZWobCv.gif">
</body>
</html>
Also, is there a more simple way to destroy an "enemy" if their hp reaches 0 than using splice in animation frame?