1

I have been trying to figure out how to detect collisions in Phaser.js 3, but I cannot find any working solutions. Here is my phaser code:

var gameState = {};

function preload() {
  this.load.image('codey', 'https://content.codecademy.com/courses/learn-phaser/codey.png');
  this.load.image('coin', 'coin.png');
}

function create() {
  gameState.cursors = this.input.keyboard.createCursorKeys();
  gameState.codey = this.add.sprite(50, 50, 'codey');
  gameState.coin = this.add.sprite(Math.floor(Math.random() * 301), Math.floor(Math.random() * 301), 'coin');
}

function update() {
  if (gameState.cursors.down.isDown) {
    gameState.codey.y += 1;
  }
  if (gameState.cursors.up.isDown) {
    gameState.codey.y -= 1;
  }
  if (gameState.cursors.left.isDown) {
    gameState.codey.x -= 1;
  }
  if (gameState.cursors.right.isDown) {
    gameState.codey.x += 1;
  }
}

const config = {
  width: 300,
  height: 300,
  backgroundColor: 0xdda0dd,
  scene: {
    preload,
    create,
    update
  }
};

const game = new Phaser.Game(config);

Heres a link to the game: https://wornflamboyantpixels.frigidus5.repl.co/

winner_joiner
  • 12,173
  • 4
  • 36
  • 61
frigidus
  • 48
  • 7

1 Answers1

2

To use physics for collisions, you need to add the physics configuration to that game-config, and than add the gameObjects to the physics world.

There are several examples on the offical example archive, I sugest using arcade physics.

Here a small demo:

document.body.style = 'margin:0;';

var config = {
    width: 536,
    height: 183,
    // configure physics
    physics: {
        default: 'arcade',
        arcade: {            
            gravity:{ y: 100 },
            debug: true
        }
    },
    scene: { create }
}; 

function create () {
    this.add.text(10,10, 'Physics DEMO')
        .setScale(1.5)
        .setOrigin(0)
        .setStyle({fontStyle: 'bold', fontFamily: 'Arial'});

    let gameObject1 = this.add.rectangle(50, 50, 30, 20, 0xffffff);
    let gameObject2 = this.add.rectangle(50, 150, 30, 20, 0xff0000);
    
    // add to the physics world
    this.physics.add.existing(gameObject1);
    this.physics.add.existing(gameObject2, true);
    
    // collider  
    this.physics.add.collider(gameObject1, gameObject2,  ()=> console.info('object have collided'));
}

new Phaser.Game(config);
console.clear();
<script src="//cdn.jsdelivr.net/npm/phaser/dist/phaser.min.js"></script>

Info: If the physics are not configured they will not work.

winner_joiner
  • 12,173
  • 4
  • 36
  • 61