Search code examples
javascriptdom-eventscollision-detectionphaser-framework

Phaser.js - How to have both sprites stop moving when either of the sprites collides


I am making a game where there are 2 sprites (one dude and one wrecking ball), and both of them move when keydown. That part works fine, but I want them BOTH to stop when EITHER of them collides with walls on the side. (There is gravity too, so the sprites are constantly colliding with the floor.) So:

nothing: nothing happens
a collides: STOP!
b collides: STOP!
a AND b collides: STOP!

I have the following code snippets:

//in create()

this.wall = this.physics.add.staticGroup()

this.dude = this.physics.add.image(...getPos([7, 1]), 'dude')
this.dude.setCollideWorldBounds(true)
this.physics.add.collider(this.dude, this.wall)

this.ball = this.physics.add.image(...getPos([7, 22]), 'ball')
this.ball.setCollideWorldBounds(true)
this.physics.add.collider(this.ball, this.wall)

//in update()

if (cursors.left.isDown || this.a.isDown) {
  this.dude.setVelocityX(-300)
  this.ball.setVelocityX(-300)
  //code to manage it should go here...
} else if (cursors.right.isDown || this.d.isDown) {
  this.dude.setVelocityX(300)
  this.ball.setVelocityX(300)
  //and here...
} else {
  this.dude.setVelocityX(0)
  this.ball.setVelocityX(0)
}

if (
  (cursors.up.isDown || this.w.isDown || this.space.isDown) &&
  this.dude.body.blocked.down
) {
  //the ball is not supposed to jump when the player jumps, and should fall according to gravity, but otherwise, it should imitate the player
  this.dude.setVelocityY(-1000)
  setTimeout(() => {
    this.dude.setVelocityY(0)
  }, 250)
}

HERE ARE SOME OF THE THINGS I TRIED BUT DIDN'T WORK

• adding a callback function to colliders - the collider function couldn't distinguish between floor and wall, and I couldn't set floors to another separate class because if the dude jumps on a wall, it will become a floor:
  • .body.blocked and .touching - like other people said, when sensing for left and right, the attributes ALWAYS return false for some reason (I've tried both)
  • new phaser.point - something I found on stack used to detect change marked √, but it doesn't work (the syntax was Phaser.Point.equals(dude.body.velocity, new Phaser.Point(0,0)))

Solution

  • I found a way that works!

    It was to store the map inside an array and read off of there to check if the dude or the ball has crashed.