Colliding Phaser 3 graphics with a sprite

I’m making a game where the player is a square and the ground is made using Phaser graphics.

create() {
  //add the player here
  this.player = this.physics.add.sprite(20, 400, localStorage.getItem("square"));
  this.player.setGravityY(1200);
  this.player.setCollideWorldBounds(true);

  //add the ground graphics here
  this.ground1 = this.add.graphics();
  this.ground1.fillRect(0, 500, 1000, 100);
  
  //I want to make the player collide with the graphics so that it acts as ground
  this.physics.add.collider(this.player, this.ground1);
}

Does anyone know if it is possible to make graphics have physics and to make it collide with a sprite. I have tried this.physics.add.existing(this.ground1); but that doesn’t seem to do anything.

:wave:

It is possible but you need to use setBodySize() or body.setSize() because a Graphics object doesn’t have an intrinsic size. I think there’s an example, I’ll look.

For your case you might find it simpler to use this.add.rectangle(…) as you won’t have that problem.

Turn on physics debug to confirm the body dimensions are correct.

1 Like

Thank you Samme! I’ll try using that :slight_smile: