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

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.

Guest
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.

Loading...
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.