How to add custom sprite to a group

How to add a custom sprite which extends Phaser.GameObjects.Sprite to a group

— Ball JS —

export default class extends Phaser.GameObjects.Sprite {
constructor (config) {
super(config.scene, config.x, config.y, config.asset)
config.scene.physics.world.enable(this);
this.body.gravity.y = 2000;
this.body.setBounce(1);
this.body.setCircle(25);
}
}

-------------- Game JS
import Ball from ‘…/Ball’

this.ballGroup = this.add.group();

this.ball = new Ball({
scene: this,
x: this.game.config.width/6,
y: this.game.config.height/2,
asset: ‘ball’
})
this.ballGroup.add(this.ball);

Note : this.add.exisiting(this.ball) works fine

Maybe something like this?

export default class extends Phaser.Physics.Arcade.Sprite {
  constructor(scene, x, y, texture) {
    super(scene, x, y, texture)

    scene.add.existing(this)
    scene.physics.add.existing(this)

    this.body.gravity.y = 2000
    this.body.setBounce(1)
    this.body.setCircle(25)
  }
}
import Ball from '…/Ball'

this.ballGroup = this.add.group()
this.ball = new Ball(this, this.game.config.width/6, this.game.config.height/2, 'ball')
this.ballGroup.add(this.ball)
1 Like

Thanks

I also have a question about custom objects. I use lots of custom objects and the gamescene can be restarted a couple of times, for different levels or after game over.

Will the custom objects be properly destroyed and removed from memory? I know JavaScript has automatic garbage collection, but if you do something like this:

// add 50 balls
for (var i=0; i < 50; i++) {
    var ball = new Ball(this, this.game.config.width/6, this.game.config.height/2, 'ball')
    this.ballGroup.add(ball)
};

The custom Ball objects created with new are added to both the scene AND the ballGroup. So will they be destroyed and removed from memory when the scene is restarted? Or are they still referenced by the scene causing some sort of memory leak?

When the scene shuts down it removes its own references to sprites and groups.