Jump to content

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. 

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 ;)

Link to post
Share on other sites
  • 2 years later...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Create New...