What is the best way to handle multiples objects? I have created 5 of them, but I can work around with only one. What should I do to handle all objects in my ‘moveEnemy’ functions?
//scene.js
create() {
for (var i = 0; i < 5; i++) {
this.enemy = this.physics.add.existing(new Enemy(this)); //I've messed up here.
}
update() {
this.moveEnemy(this.enemy);
}
moveEnemy(enemy) {
if (enemy.y > config.height) {
this.resetPos(this.enemy);
}
}
resetPos(enemy) {
this.enemy.y = Phaser.Math.Between(-200, 0);
this.enemy.x = Phaser.Math.Between(0, config.width);
}
//enemy.js
class Enemy extends Phaser.GameObjects.Sprite {
constructor(scene) {
var x = Phaser.Math.Between(0, config.width);
var y = Phaser.Math.Between(-500, -50);
super(scene, x, y, "enemy");
this.scene.add.existing(this);
this.scene.physics.world.enableBody(this);
this.body.velocity.y = 100;
}
In my game (A space shooter, so lots of enemies and bullets flying around), every unique gameobject gets their own group. In those groups, runChildUpdate is set to true so that the custom update method I provide in the enemy classes is run during the update frame. From here, I do all of the movement/management/etc. inside the enemy’s update method. The nice thing about this approach is that things like collision scale much easier when you get a lot of different types of objects interacting, and pooling to improve performance is only a matter of populating the groups ahead of time.