Skip to content

Instantly share code, notes, and snippets.

@videlais

videlais/script.js Secret

Created Aug 28, 2015
Embed
What would you like to do?
Phaser Physics -- Collision Example
var game = new Phaser.Game(
200, //The width in pixels
200, //The height in pixels
Phaser.AUTO, //The render system
"phaser", //The element
{
preload: preload, // The preload function
create: create, // The create function
update: update // The update function
}
);
// Create the variables outside of any one function scope
var sprite;
var sprite2;
function preload() {}
function create() {
// Set the 'game.stage' to a color
game.stage.backgroundColor = '#2d2d2d';
// Start the Arcade physics system
game.physics.startSystem(Phaser.Physics.ARCADE);
sprite = game.add.sprite(
50, // The x position
20, // The y position
'sprite' // The image cache-key
);
sprite2 = game.add.sprite(
50, // The x position
150, // The y position
'sprite' // The image cache-key
);
// Enable Arcade physics on 'sprite'
game.physics.arcade.enable(sprite);
// Enable Arcade physics on 'sprite2'
game.physics.arcade.enable(sprite2);
// Make sure 'sprite' does not leave the world
sprite.body.collideWorldBounds = true;
// Make sure 'sprite2' does not leave the world
sprite2.body.collideWorldBounds = true;
// Set a velocity for 'sprite'
sprite.body.velocity.y = 40;
// Set an equal velocity for 'sprite2'
sprite2.body.velocity.y = -40;
}
function update() {
// Check if 'sprite' and 'sprite2' collide with each other
game.physics.arcade.collide(
sprite, // The first entry
sprite2, // The entry to check against
collisionCallback, // The collision callback
processCallback // The process callback
);
}
function collisionCallback(object1, object2) {
// When they collide, set the background to a different color
game.stage.backgroundColor = '#992d2d';
}
function processCallback() {
// Within the process callback, we can test for extra things.
// For example, if we wanted to check if their health matched
// of if they were of different enemy types, we can do that here.
//
// For what ever we test, we need to return either true or false.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.