phaser/examples/collision/sprite vs group.js

85 lines
1.9 KiB
JavaScript
Raw Normal View History

2013-10-22 03:58:20 +01:00
var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update });
2013-10-22 03:58:20 +01:00
function preload() {
game.load.image('phaser', 'assets/sprites/phaser-dude.png');
game.load.spritesheet('veggies', 'assets/sprites/fruitnveg32wh37.png', 32, 32);
}
var sprite;
var group;
var cursors;
2013-10-22 03:58:20 +01:00
function create() {
game.stage.backgroundColor = '#2d2d2d';
// This example will check Sprite vs. Group collision
2013-10-22 03:58:20 +01:00
sprite = game.add.sprite(32, 200, 'phaser');
sprite.name = 'phaser-dude';
group = game.add.group();
for (var i = 0; i < 50; i++)
{
var c = group.create(game.rnd.integerInRange(100, 770), game.rnd.integerInRange(0, 570), 'veggies', game.rnd.integerInRange(0, 36));
2013-10-22 03:58:20 +01:00
c.name = 'veg' + i;
c.body.immovable = true;
}
for (var i = 0; i < 20; i++)
{
// Here we'll create some chillis which the player can pick-up. They are still part of the same Group.
var c = group.create(game.rnd.integerInRange(100, 770), game.rnd.integerInRange(0, 570), 'veggies', 17);
2013-10-22 03:58:20 +01:00
c.name = 'chilli' + i;
2014-02-05 16:54:35 +00:00
c.body.immovable = true;
2013-10-22 03:58:20 +01:00
}
cursors = game.input.keyboard.createCursorKeys();
2013-10-22 03:58:20 +01:00
}
function update() {
game.physics.collide(sprite, group, collisionHandler, null, this);
game.physics.collide(group, group);
2013-10-22 03:58:20 +01:00
sprite.body.velocity.x = 0;
sprite.body.velocity.y = 0;
if (cursors.left.isDown)
2013-10-22 03:58:20 +01:00
{
sprite.body.velocity.x = -200;
}
else if (cursors.right.isDown)
2013-10-22 03:58:20 +01:00
{
sprite.body.velocity.x = 200;
}
if (cursors.up.isDown)
2013-10-22 03:58:20 +01:00
{
sprite.body.velocity.y = -200;
}
else if (cursors.down.isDown)
2013-10-22 03:58:20 +01:00
{
sprite.body.velocity.y = 200;
}
}
function collisionHandler (player, veg) {
2013-10-22 03:58:20 +01:00
// If the player collides with the chillis then they get eaten :)
// The chilli frame ID is 17
if (veg.frame == 17)
2013-10-22 03:58:20 +01:00
{
veg.kill();
2013-10-22 03:58:20 +01:00
}
}