I’m looking for something along the lines of this:
class Player extends Phaser.Sprite
{
constructor(scene, x, y)
{
// etc ...
// This is what I want:
this.on("collide", this.onCollide);
}
onCollide(object)
{
// Do something with `object`
// Note: `object` can be any other sprite in the entire scene
}
}
Is there any way to achieve this without having separate code for each game object in the scene? I want just like 10-20 lines of code to achieve this for all sprites of the scene.
Hi,
It seems the collide event only work within a scene
From the doc:
The Arcade Physics World Collide Event.
This event is dispatched by an Arcade Physics World instance if two bodies collide and at least one of them has their [onCollide]{@link Phaser.Physics.Arcade.Body#onCollide} property set to true.
It provides an alternative means to handling collide events rather than using the callback approach.
Listen to it from a Scene using: this.physics.world.on('collide', listener).
Please note that 'collide' and 'overlap' are two different things in Arcade Physics.
But you can do something like this in the scene:
Push every scene object to an array and add a scene collider
this.physics.add.collider(this.player, this.arrayOfObjects, this.player.onCollide(player, obj), undefined, this);