组与组之间的处理
原文地址:http://www.phaser.io/examples/v2/arcade-physics/group-vs-group。
效果
源代码
window.onload = function () { var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser_container', { preload: preload, create: create, update: update }); function preload() { game.load.image('phaser', 'images/phaser/phaser-dude.png'); game.load.image('bullet', 'images/phaser/bullet0.png'); game.load.spritesheet('veggies', 'images/phaser/fruitnveg32wh37.png', 32, 32); } var sprite; var bullets; var veggies; var cursors; var bulletTime = 0; var bullet; function create() { game.stage.backgroundColor = '#2d2d2d'; // 检测组(子弹)与组(蔬菜)之间的碰撞 (bullets vs. veggies!) veggies = game.add.group(); veggies.enableBody = true; veggies.physicsBodyType = Phaser.Physics.ARCADE; for (var i = 0; i < 50; i++) { var c = veggies.create(game.world.randomX, Math.random() * 500, 'veggies', game.rnd.integerInRange(0, 36)); c.name = 'veg' + i; c.body.immovable = true; } bullets = game.add.group(); bullets.enableBody = true; bullets.physicsBodyType = Phaser.Physics.ARCADE; for (var i = 0; i < 20; i++) { var b = bullets.create(0, 0, 'bullet'); b.name = 'bullet' + i; b.exists = false; b.visible = false; b.checkWorldBounds = true; b.events.onOutOfBounds.add(resetBullet, this); } sprite = game.add.sprite(400, 550, 'phaser'); game.physics.enable(sprite, Phaser.Physics.ARCADE); cursors = game.input.keyboard.createCursorKeys(); game.input.keyboard.addKeyCapture([Phaser.Keyboard.SPACEBAR]); } function update() { // 本例只检测相交,而无需进行碰撞处理 game.physics.arcade.overlap(bullets, veggies, collisionHandler, null, this); sprite.body.velocity.x = 0; sprite.body.velocity.y = 0; if (cursors.left.isDown) { sprite.body.velocity.x = -300; } else if (cursors.right.isDown) { sprite.body.velocity.x = 300; } // 按空格键发射子弹 if (game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR)) { fireBullet(); } } function fireBullet() { if (game.time.now > bulletTime) { bullet = bullets.getFirstExists(false); if (bullet) { bullet.reset(sprite.x + 6, sprite.y - 8); bullet.body.velocity.y = -300; bulletTime = game.time.now + 150; } } } // 销毁飞出屏幕的子弹 function resetBullet(bullet) { bullet.kill(); } // 若子弹打中蔬菜,则销毁两者 function collisionHandler(bullet, veg) { bullet.kill(); veg.kill(); } }
发布时间:2016/11/19 下午9:46:46 阅读次数:4927