Jump to content

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


mhcdotcom
 Share

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. 

Link to comment
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
)

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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