Jump to content

Randomly timed event?


hellspawn_bg
 Share

Recommended Posts

I am trying to implement some random events happening in my game. For example I want to drop an item on every 5 to 10 seconds. In phaser there is an easy way to create loop events, but they all loop at a certain time. What I am doing so far to achieve this is to add a delay on the event in the timer callback. Is there a smart way to create create events looping in some time range?

// Initialize drop timervar cooldown = this.game.rnd.realInRange(this.coolMin, this.coolMax);this.dropTimer = this.game.time.create(false);this.dropEvent = this.dropTimer.loop(Phaser.Timer.SECOND * cooldown, this.dropItem, this);this.dropTimer.start();// dropItem function Grabbable.prototype.dropItem= function() {        // Do something    // Reset timer    var cooldown = this.game.rnd.realInRange(this.coolMin, this.coolMax);    this.dropEvent.delay = Phaser.Timer.SECOND * cooldown;};
Link to comment
Share on other sites

There's no random time method, but with a bit of code wrapped around a timer you could do this:

this.dropTimer = this.game.time.create(false);this.dropTimer.start();Grabbable.prototype.dropItem = function() {  // Do something  this.dropTimer.add(Phaser.Timer.SECOND * this.game.rnd.realInRange(this.coolMin, this.coolMax, this.dropItem, this);}; 

So rather than looping, every time dropItem is called it adds another single timer event to call itself. Then all you have to do is call this.dropItem() the first time, and it'll continue firing randomly until the timer is stopped or the callback is removed.

Link to comment
Share on other sites

I don't think you'll need to worry too much about performance with this, but if you are really bothered, a more lightweight way of doing this would be to just do the following and avoid timers altogether (assumes Grabbable has an update function to call, if not, you'll have to do this in your main game update):

Grabbable.prototype.update = function() {  if (this.game.time.now > this.nextEvent) {    this.updateNextEvent();    // Do something  }};Grabbable.prototype.updateNextEvent = function() {  this.nextEvent = this.game.time.now + (this.game.rnd.realInRange(this.coolMin, this.coolMax) * 1000);};
Link to comment
Share on other sites

Don't know if its more or less efficient but I would have gone with a 1 second repeating timer and put the randomised logic in the callback function. Most of the time it does nothing but decrements a counter. When the counter hits zero your dropItem function fires and the counter gets reset to a random number between 5 and 10.

Edit: hmmm actually that prob not very efficient. Nvm

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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