Reputation: 53
So, what I am trying to accomplish is a damage system, so when an enemy is near the player (within where the player is on the screen) they take damage. However, since there are multiple enemies on the screen at one time I don't want the player to get stack bombed by 10 and immediately die. So here was my solution though.
createjs.Ticker.addEventListener("tick", damage1);
function drop() {
if (eX > p1.x - 40 && eX < p1.x + 40) {
health -= 1;
console.log("Health is: " + health);
}
}
function damage1() {
for (x = 0; x < enemy.length; x++) {
eX = enemy[x].x;
eY = enemy[x].y;
if (eY > p1.y - 25 && eY < p1.y + 25) {
setTimeout(drop, 2000);
}
}
}
This however doesn't work how I expected. What I thought would happen is if the if statement passed, it would get to set timeout, wait 2 seconds, and then get to the function where it takes away health. However what actually happens is it gets to the timeout, waits 2 seconds, and then runs the takeaway health command once every tick, so it only waits the one time.
I am working in adobe animate, html5 canvas if that changes anything
Upvotes: 2
Views: 1026
Reputation: 833
Even with a proper delay, iterating through the length of enemies would still take away the same amount of health, only with, yeah.. a delay.
What I would do instead is take away the health, disable hit detection, then set a timer during which the player is invulnerable. This way the player takes one hit at a time and has time to run away.
Upvotes: 2
Reputation: 1820
The setTimeout
function gets called essentially at the same time, but enemy.length
times, because each iteration of the for loop doesn't wait for the setTimeout
callback to finish. If you add a console.log
into the drop
function, you'll see that it is called multiple times. If you want the delay added per index in the for loop, you could change to:
setTimeout(drop, 2000 * (x + 1))
Upvotes: 2