How to detect collision event with an unknown object?

Hi everyone, I’m trying to add a collision event to detect an object from another class

So here the thing, I want to make the game to be OOP, so every object has its own class logic. Let’s say Food.ts contains the logic of the food, player contains the logic of the player.

In order to detect collision, I’ve read everywhere on Phaser3 and this place, found nothing but only doing something like this.physics.add.collider(food, player, callback), and I have to call this function in the scene, that’s kind of ruining the OOP pattern (because now the logic of collision is in the scene file, not in the food or player either). And I really don’t like this approach.

I found another way which is very promise is using this.physics.world.on(‘collide’, callback), and using it inside food or player. But I can’t make it work, the callback has never been fired. I’ve read that collide event using this.physics.world.on(‘collide’) will be fired if one of the two objects has onCollide property. So I make sure I’ve already turned it on. But still no hope.

If I using MatterJS, they have something like onCollideCallback of the gameobject. And it will be fired whenever the game object hits something.

The physics engine I using is Arcade.

Any ideas?

:wave:

this.physics.add.collider(player, food, () => {
  player.onCollideWithFood();
  food.onCollideWithPlayer();
});

Phaser.Physics.Arcade.Events.COLLIDE is maybe not a good choice here because it fires for every collision of every game object.

Wow, this is it!
The last one, so there is no callback in Arcade physics that I can attach to the body at all?

Arcade Physics bodies can’t emit events, but I guess you could do

this.physics.world.on('collide', (gameObject1, gameObject2) => {
  gameObject1.emit('collide', gameObject2);
  gameObject2.emit('collide', gameObject1);
});

Love that. Thank you!