Jump to content

Is it possible to add timed events for sprites?


Recommended Posts

For example, I have a bullets group with 5 children as sprites.


I use 

var bullet = bullets.getFirstDead();

To grab the first available bullet.


But, I want to call 'bullet.kill()' on this sprite after 2 seconds if it hasn't been killed already.


So I use:

setTimeout(function(bullet){     bullet.kill();					}, 2000, bullet);

The problem is, if this bullet hit's a monster in my game within 2 seconds, it's already killed; so then when the user shoots another bullet, the setTimeout will come back and bite me in the ass and remove the bullet after that time difference.


So is it possible to add some type of timer event that attaches to each individual sprite as a separate entity and checks how long it's alive and then removes it after a certain amount of time if it hasn't been killed? If that makes sense, I'm bad at explaining things.  

Link to comment
Share on other sites

After some thought and thinking about my issue, I have a hacky solution. Multiple Personality Disorder Post Incoming:


The problem you have is that getFirstDead() is grabbing the first available child that is not alive (dead), so when your bullet comes into contact with a Monster before the 2000 ms interval is up, it will destroy it. And the reason why is because when you're firing a new bullet (when your older one is destroyed), getFirstDead() is still grabbing the same sprite (the first dead one), thus kill() will be used on the same one.


What I recommend is doing:

bullet.startTime = Date.now()/1000;

Which will get you a unixTimestamp and then change your setTimeout to:

setTimeout(function(a){if(Date.now()/1000 - a.startTime == 2){a.kill();}}, 2000, bullet);

This way, each new bullet that gets fired will check if it's really been 2 seconds elapsed (if it's not 2 seconds, kill() was called when it hit a monster) and the if condition will fail. This works because .startTime property is   isolated with every new bullet.

Link to comment
Share on other sites

Sounds exactly like something I did in Blaster: https://github.com/drhayes/blaster/blob/master/src/sprites/bullet.js


Do the "getFirstDead" stuff from the group, then call the bullet's "fire" method. The "fire" method sets the timer to kill itself. The kill method makes sure to stop the timer for when the bullet gets recycled.

Link to comment
Share on other sites


  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Create New...