What is the best way to handle multiples objects?

Hello,

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;
}

Hi,
I handle enemies individually in their own class, moveEnemy and resetPos should go in the Enemy class

Thank you for your reply!!!

How do I do it? My class only runs once. So it won’t have it tracked by my moveEnemy and resetPos functions.

Thank you!!

Here’s an example of an enemy class

class Enemy extends Phaser.GameObjects.Sprite {
  constructor(scene, x, y, config) {
    super(scene, x, y, config.key);

    this.scene = scene;
    this.scene.physics.world.enable(this);
    this.scene.add.existing(this);
  }

  preUpdate(time, delta) {
    super.preUpdate(time, delta);
    if (this.active && this.body.blocked.down) {
      // here's the logic of your enemy
      this.body.setVelocityX(50)
    }
  }

  moveEnemy() {
    if (this.y > this.scene.height) {
      this.resetPos(this);
    }
  }
 
  resetPos() {
    this.y = Phaser.Math.Between(-200, 0);
    this.x = Phaser.Math.Between(0, this.scene.width);
  }
}

Collect them in an array and iterate.

class Scene {
  create () {
    this.enemies = [];

    for (var i = 0; i < 5; i++) {
      this.enemies[i] = this.physics.add.existing(new Enemy(this));
    }
  }

  update () {
    this.enemies.forEach(this.moveEnemy, this);
  }

  moveEnemy (enemy) {
    // …
  }
}
1 Like

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.

1 Like