Jump to content

Ticking time bomb in a game


eyo_omat
 Share

Recommended Posts

I am trying to create a bomb that only goes off after the player has collides with it but delays for a number of seconds. Currently it goes off immediately

I have my collision as below

game.physics.arcade.collide(this.player, this.tnts, this.tntCollision, null, this);

and the collison handler as below

tntCollision: function (player, tnt) {
    if (player.body.touching.right){
        player.body.velocity.x = -200;
    } else if (player.body.touching.down) {
        tnt.kill();
        var explosionGroup = "explosionSmallGroup";
        var explosion = this[explosionGroup].getFirstExists(false);
        explosion.reset(tnt.x, tnt.y);
        explosion.animations.play('explode', 30, false, true);
    } else if (player.body.touching.left) {
        player.body.velocity.x = 200;
    }
}

 

 

 

Link to comment
Share on other sites

You're pretty much there you just need to delay things a little, `setTimeout` is your simplest friend here:

const DELAY = 2000

tntCollision: function (player, tnt) {
  setTimeout(function () {
    ...do stuff
  }, 2000)
}

Bare in mind that, depending on the rest of the code, you need to make sure that `player` and `tnt` are representative of the state in 2 seconds time, usually (due to closure) those variables can become locked to when the call was initiated, try it and see.

In your case it looks like your `tntCollision` function wants to do some work when the collision occurs and some other work in 2 seconds (for example) time so you'll have to dice it up how you see fit and use setTimeout to schedule a function to invoke after a set number of milliseconds.

Also, Phaser has an idiomatic way of scheduling functions in the future so you shouldn't need to call setTimeout explicitly, have a google (or search these forums) for Phaser.Timer events (I think thats what its called).

Link to comment
Share on other sites

When using Phaser, I would really recommend using the game.time helper, and not setTimeout.

const myTimer = game.time.create()
myTimer.add(duration, callback, context)
myTimer.start()

This will make it a lot easier if you are ever going to create a pause button in your game. The default js setTimeout will just keep going, but the Phaser built-in one will pause as well when you flip the pause bool in Phaser.

Link to comment
Share on other sites

2 hours ago, mattstyles said:

Also, Phaser has an idiomatic way of scheduling functions in the future so you shouldn't need to call setTimeout explicitly, have a google (or search these forums) for Phaser.Timer events (I think thats what its called).

Yes, it might be better to use Phaser's own functionality:

game.time.events.add(2000, function() {
  //code
}, this);

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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