Jump to content

Best way to trigger something on bounce


Zweiblumen
 Share

Recommended Posts

With:

player.body.collideWorldBounds = true;player.body.bounce.set(1);

I get the nice effect of bouncing off the walls, but I'd like for something (say, a score counter) to be updated every time player collides with the bounds. What is the best way of doing this with Phaser?

Link to comment
Share on other sites

There is not an event for that, but you can resolve it easily.

You could create some other invisible sprites to collide with, or use something similar to the internal method that Phaser uses to manage it:

 



/**
* Internal method.
*
* @method Phaser.Physics.Arcade.Body#checkWorldBounds
* @protected
*/
checkWorldBounds: function () {

if (this.position.x < this.game.physics.arcade.bounds.x && this.game.physics.arcade.checkCollision.left)
{
this.position.x = this.game.physics.arcade.bounds.x;
this.velocity.x *= -this.bounce.x;
this.blocked.left = true;
}
else if (this.right > this.game.physics.arcade.bounds.right && this.game.physics.arcade.checkCollision.right)
{
this.position.x = this.game.physics.arcade.bounds.right - this.width;
this.velocity.x *= -this.bounce.x;
this.blocked.right = true;
}

if (this.position.y < this.game.physics.arcade.bounds.y && this.game.physics.arcade.checkCollision.up)
{
this.position.y = this.game.physics.arcade.bounds.y;
this.velocity.y *= -this.bounce.y;
this.blocked.up = true;
}
else if (this.bottom > this.game.physics.arcade.bounds.bottom && this.game.physics.arcade.checkCollision.down)
{
this.position.y = this.game.physics.arcade.bounds.bottom - this.height;
this.velocity.y *= -this.bounce.y;
this.blocked.down = true;
}

}

If you look how checkWorldBounds is implemented you can see that "blocked" property during one frame:

 


 

So we could text this property in the update something like this:

 



function update() {

if (mySprite.body.blocked.up === true) {
console.log("Hit!");
game.stage.backgroundColor = '#992d2d';

};
if (mySprite.body.blocked.down === true) {
console.log("Hit!");
game.stage.backgroundColor = '#996633';

};
if (mySprite.body.blocked.left === true) {
console.log("Hit!");
game.stage.backgroundColor = '#cc3399';

};
if (mySprite.body.blocked.right === true) {
console.log("Hit!");
game.stage.backgroundColor = '#666666';
};

}

It is not the best solution I think, but it could be useful in some cases, here it is a working example:

 


 


Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...