Sign in to follow this  
mhcdotcom

How can I have a Collider callback occur only once?

Recommended Posts

Hey All,

I hope you can help me. I'm quite new to Phaser. I've looked all over google and couldn't find an answer to my question.
I have an idea for a Tetris-like game. 
At the moment I'm learning the basics by setting up a single block to fall on the floor before another single block falls after it.
The block falls from the air onto the ground just fine. The issue is:
I simply want to have a collision call back happen once.
I've simplified the code to make the question easier to read:

function create () {  
  this.physics.add.collider(block, ground, hitFloor, null, this);
}
function hitFloor () {
  console.log('floor hit');
}

The block hits the floor and the callBack runs infinitely which makes sense because the block doesn't move and stays on the floor.  I was considering setting a flag with a variable like `floorHit`.
Something like: 

function hitFloor() {
  if (!floorHit) {
   console.log('do something')
   floorHit = true
  }
}

But I want to have multiple blocks fall and this won't work because the new block that gets created needs to have the `floorHit` variable set to false before it starts falling. 
What am I missing?
Any help would be much appreciated. 
Thanks
MHC

Share this post


Link to post
Share on other sites
// I would prefer ES6 syntax with this.colliderActivated. But that's up to you.
// colliderActivated holds a Boolean
let colliderActivated = true;


function create () {  
  // colliders have the 4th parameter for a collision check, just return your variable
  this.physics.add.collider(block, ground, hitFloor, ()=>{
    return colliderActivated;
  }, this);
}
function hitFloor () {
  // setting colliderActivated to false, so it will return false in the collision check 
  // and the collision no longer happens.
  colliderActivated = false;
  console.log('floor hit');
}

 Here you go ;)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.