What is the best way to handle GameObjects update function?

Hello all.

I’m new to gamedev, but I’m a javascript developer for many years. So I’m trying my luck with Phaser while making some games, but many times I question myself if what I’m doing is the correct way of doing it or not.

So for example, I have a stage with a bunch of enemies that have their own logic (for movements and other things), so the way I’m doing it is:

class Scene {
    create() {
        this.enemies = [];
        new Array(10).fill(null).forEach(() => {
            this.enemies.push(new Enemy(this));
        });
    }

    update() {
        this.enemies.forEach((enemy) => {
            enemy.update();
        });
    }
}

Is this the correct way of doing it? Because it feels very hacky to loop on every frame and call the enemy’s update function.

Even if that’s the correct way, is there another cost-equivalent way of doing it? Just so I can weight in my options.

Thank you

This is a good way to do it, especially if you want to control exactly when your enemies update.

If you want Phaser to update your enemies by itself, you can add a preUpdate method to your Enemy class; scene.add.existing will automatically register it to run every frame. If the superclass already has a preUpdate method, make sure to call it (a Sprite, for example, uses it to update its animations). Keep in mind that preUpdate, as its name suggests, will run before your scene’s update method.

You can also manually register a listener for one of the update events. You will also have to manually clean up your listener when the Enemy is destroyed.

1 Like

Telinc1 Thats awesome, thanks, exactly what I was looking for. Which one of these is the fastest / most efficient?

There’s no significant difference. All of them run off the same event system.

1 Like

Group with runChildUpdate also works for this.

2 Likes