Jump to content

Help connecting an extended class to the core game loop


GregDev
 Share

Recommended Posts

Hi all,

I have a scene and a player, the player needs do something in the core game loop.

Whenever I run into a situation like this I always end up creating an update method on the sprite/image/whatever and calling it from the scene like this:

class Level1 extends Phaser.Scene {
    constructor () {
        this.player = new Player()
    }

    update () {
        this.player.updatePlayer()
    }

}

class Player extends Phaser.Physics.Matter.Image {

    updatePlayer(){
        //do something
    }
}

It doesn't look too bad in this example, but I find things get messy once you start dealing with half a dozen game objects that all need to updated, sometimes I'll need to check if any of the game objects exist before calling their update method, adding to the mess.  

Is there a better way to do this? I know Unity/Unreal have game objects with update methods that just work™ without any need to connect them to the game's main update loop

Thanks!

Link to comment
Share on other sites

5 hours ago, Stephan said:

You can use preUpdate() function in the player class. It is being called each cycle without having to active it manually.

Appreciate the response, calling preUpdate() doesn't seem to do anything for me, I tried with the player and scene class out of curiosity. 

I had a look at the player class with the chrome debugger and I couldn't find any preUpdate() function, is there something I have to do to get it setup? 

EDIT

Nevermind, it wasn't working because I needed to add the player to the scene

 

Edited by GregDev
Link to comment
Share on other sites

Full code looks like this in case anyone else has the same issue: 
 

class Player extends Phaser.Physics.Matter.Image {
    constructor (config) {
        super(
          config.scene.matter.world,
          200,
          200,
          'assetKey'
        )
        this.scene = config.scene
        this.scene.add.existing(this)
    }

    preUpdate (time, delta) {
        //it works!
    }

}

 

Edited by GregDev
preview code
Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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