Phaser - How to properly implement Arcade Physics Collisions with Phaser.js

1.5k views Asked by At

I've scanned the web for some tutorials and looked at the documentation but it just seems to get me more confused.

The problem:

All sprites have their physics initialised in this code:

// Store all Sprites in an Array for easy access
var x64_guys = [Player, Dave, EvilDave];

// Sprite physics properties. Give the little guys some life.
hal.physics.arcade.enable(x64_guys, Phaser.Physics.ARCADE);

for(var j=0; j<x64_guys.length;j++){
    x64_guys[j].body.collideWorldBounds = true;
    x64_guys[j].body.bounce.x = true;
    x64_guys[j].body.bounce.y = true;
}

Where hal is equal to new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.AUTO, "stage", { preload: preload, create: create, update: update });

Now I am assuming this works fine to initialise physics like this?

If so then I am rather confused on how to detect Player and EvilDave collisions, and also launch a function on collide (e.g. Player death or EvilDave getting hurt). (Chars are 64x64 pixels)

If anyone could help me I'd be grateful.

1

There are 1 answers

3
PhotonStorm On BEST ANSWER

Are Player, EvilDave, etc instances of Sprites? You don't show the code so it's hard to be sure.

The call to enable physics should be like this:

hal.physics.arcade.enable(x64_guys);

Although I would get out of the practise of using 'hal' at all and instead use 'this'. You don't need the constant as the 2nd argument because you're enabling direct on the Arcade Physics manager anyway.

Is all of the above code happening in the create function? If not, it should be.

This is also wrong: body.bounce.x = true; Bounce is a Phaser.Point object, not a boolean, so it expects a value to be assigned to it. If you want to enable 100% fully reflective bouncing then set it to 1: body.bounce.x = 1;

To check collision between Player and EvilDave you need to add this to your update function:

function update() {

    // object1, object2, collideCallback, processCallback, callbackContext
    game.physics.arcade.collide(Player, EvilDave, collisionHandler, null, this);

}

function collisionHandler (obj1, obj2) {

    //  The two sprites are colliding
    game.stage.backgroundColor = '#992d2d';

}

You can see the full code for this in the Sprite vs. Sprite example on the site. Would be well worth looking over that carefully.