Armin Imamovic
Armin Imamovic

Reputation: 29

How to i correctly detect object collisions in phaser 3?

I have a problem, i need to detect when 2 containers collide, but my collision is detected before the objects even start moving, that is before there is any collision on screen. The stopMovement() callback is executed right away, before any collision happens. Any phaser experts to help?

 const move1 = setInterval(() => {
  container1.x += 1
}, 20);

const move2 = setInterval(() => {
  container2.x -= 1
}, 20);

this.gameInstance.physics.add.collider(container1, container2, this.stopMovement(move1, move2), null, this)

Upvotes: 1

Views: 1778

Answers (1)

Hendry
Hendry

Reputation: 900

In the provided code you are calling this.stopMovement(move1, move2) right away, that's why the movement stops.

Correct would be to create a function or a inline anonymous function, which you assign to the this.gameInstance.physics.add.collider callback.

Examples

Inline anonymous function

this.gameInstance.physics.add.collider(container1, container2, () => this.stopMovement(move1, move2), null, this)

Separate function

function colliderCallbackHandler() {
  this.stopMovement(move1, move2)
}

this.gameInstance.physics.add.collider(container1, container2, colliderCallbackHandler, null, this)

Upvotes: 2

Related Questions