Ajedi32
Ajedi32

Reputation: 48438

Detect impact force in Phaser with P2JS

When running a Phaser with the P2JS Physics engine, I know that it's possible to detect collisions with Phaser.Physics.P2.Body#onBeginContact. But is there a way to test the impact force of the collision, so that I can apply a realistic level of damage to my spaceship when it collides with an asteroid?

Upvotes: 2

Views: 1346

Answers (2)

Ben
Ben

Reputation: 191

You can determine the momentum of the impact using Phaser.Physics.P2.Body#onBeginContact like so:

Create your ship and add the onBeginContact signal handler to it's P2 body

ship.body.onBeginContact.add(contactHandler);

The contactHandler event will be sent 4 parameters: The body it is in contact with, the shape from this body that caused the contact, the shape from the contact body and the contact equation data array.

function contactHandler(body, shape1, shape2, equation) {

    //get the velocity of asteroid at point of contact
    var v = body.velocity.y;

    //and the asteroid's mass
    var m = body.mass;

    //calculate momentum
    var momentum = m*v;

    //momentum affects ship damage
    ship.damage(momentum);

}

Note in this example that I'm just using the vertical velocity of the asteroid to calculate the momentum. For a more accurate calculation use both the ship's and asteroid's velocities... something like this:

var v1 = new Phaser.Point(ship.velocity.x, ship.velocity.y);
var v2 = new Phaser.Point(body.velocity.x, body.velocity.y);

// calculate difference 
var v = Math.abs( v1 - v2 );

Here's the code in action: http://jsfiddle.net/bstevens/a6paycw6/

Upvotes: 2

2016rshah
2016rshah

Reputation: 681

Well the easiest way I could think of off the top of my head would be to take the asteroid objects velocity into account. So if the asteroid is coming down on the ship from the top of the screen and the asteroids y-velocity is say greater than 200 add more damage then you would add for the y-velocity being say 100. I'm not sure what the actual numbers in your game are but I think the concept of using the velocity of the asteroid still stands.

--Edit--

Say you have a spaceship and an asteroid and they have collided (vertically with spaceship towards bottom of screen) and now you are in a method that will reduce the health of the spaceship based on how hard the collision was the if statement would look something like this:

if(asteroid.body.velocity.y<100)
    spaceship.health-=10;
else if(asteroid.body.velocity.y<200)
    spaceship.health-=20;
else
    spaceship.health-=30;

(Also to make the numbers a bit more realistic I changed the y velocity values. I realize now that a y-velocity of 20 is actually quite slow and 100-300 makes a bit more sense)

Upvotes: 1

Related Questions