Sign in to follow this  
mhcdotcom

How can I call a function in a class from a collider method?

Recommended Posts

Hey All,  

I'm using WebPack to build my game and I've run into a scoping issue. I'll try and explain.
Below is my TestScene scene/class. 

import 'phaser';
import Npcs from 'modules/Npcs.js';

const npcs = new Npcs()

export class TestScene extends Phaser.Scene {

  constructor () {
    super('TestScene')
  }

  preload(){...}

  create(){
    this.physics.add.collider(
      this.player,
      this.bombs,
      npcs.hitBomb,
      null,
      this
    )
  }

}

Below is my npcs class

import 'phaser';

const gameplayStates = new GameplayStates()

export default class Npcs {

  hitBomb (player, bomb) {
    this.physics.pause();
    player.setTint(0xff0000);
    this.entityDestroy()
  }

  entityDestroy () {
  console.log('destroyed')
  }

}

`this.player` and `this.bombs` are in place and work as expected in every way I intended. 

The callback in the collider method has `this`(testScene) as the context so, `this.entityDestroy()` no longer seems to work and fires

app.bundle.js:116068 Uncaught TypeError: this.entityDestroy is not a function

I suspect this is because the `npcs` class is not in the npcs class' scope when the method is called from the collider function. 

How can I get around this with the collider method?

Your help would be much appreciated.

Thanks all, 

Your help is much appreciatd. 

Share this post


Link to post
Share on other sites

I think you'll have a problem in hitBomb either way because the two this keywords are intended to reference different objects.

So I would do this:

this.physics.add.collider(
  this.player,
  this.bombs,
  function (player, bomb) {
    this.physics.pause();
    npcs.hitBomb(player, bomb);
  },
  null,
  this
)

 

Share this post


Link to post
Share on other sites
On 11/1/2018 at 2:59 PM, samme said:

 


this.physics.add.collider(
  this.player,
  this.bombs,
  function (player, bomb) {
    this.physics.pause();
    npcs.hitBomb(player, bomb);
  },
  null,
  this
)

 

This worked a treat. Thank you.
 

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.