Jump to content

How can I call a function in a class from a collider method when this is a different scope?


mhcdotcom
 Share

Recommended Posts

As you can see in here: https://photonstorm.github.io/phaser3-docs/Phaser.Physics.Arcade.Factory.html#collider__anchor
the method takes a callback, but also as a last parameter it takes a context. So instead of doing this:

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

Do this:

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

Because now you pass a context to the callback (npcs.hitBomb) the npc's context. If you ever run into a situation where a method would not give you the possibility to pass a context you can look into .bind:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind

Lambdas are also a great way to work around it but I would not recommend that for how you want to use it (calling a method on another object)
 

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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