-
-
Save videlais/c45cebb4c40417b3c80a to your computer and use it in GitHub Desktop.
Phaser Physics -- Collision Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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