发射子弹

原文地址:http://www.phaser.io/examples/v2/arcade-physics/shoot-the-pointer。

效果

源代码

window.onload = function () {
    var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser_container', 
                            { preload: preload, create: create, update: update ,render:render });

    function preload() {

        game.load.image('arrow', 'images/phaser/arrow.png');
        game.load.image('bullet', 'images/phaser/purple_ball.png');

    }

    var sprite;
    var bullets;

    var fireRate = 100;
    var nextFire = 0;

    function create() {

        game.physics.startSystem(Phaser.Physics.ARCADE);

        game.stage.backgroundColor = '#313131';

        bullets = game.add.group();
        bullets.enableBody = true;
        bullets.physicsBodyType = Phaser.Physics.ARCADE;

        bullets.createMultiple(50, 'bullet');
        bullets.setAll('checkWorldBounds', true);
        bullets.setAll('outOfBoundsKill', true);

        sprite = game.add.sprite(400, 300, 'arrow');
        sprite.anchor.set(0.5);

        game.physics.enable(sprite, Phaser.Physics.ARCADE);

        sprite.body.allowRotation = false;

    }

    function update() {

        sprite.rotation = game.physics.arcade.angleToPointer(sprite);

        if (game.input.activePointer.isDown) {
            fire();
        }

    }

    function fire() {

        if (game.time.now > nextFire && bullets.countDead() > 0) {
            nextFire = game.time.now + fireRate;

            var bullet = bullets.getFirstDead();

            bullet.reset(sprite.x - 8, sprite.y - 8);

            game.physics.arcade.moveToPointer(bullet, 300);
        }

    }

    function render() {

        game.debug.text('Active Bullets: ' + bullets.countLiving() + ' / ' + bullets.total, 32, 32);
        game.debug.spriteInfo(sprite, 32, 450);

    }
}

发布时间:2016/11/26 下午9:55:46  阅读次数:4498

2006 - 2024,推荐分辨率 1024*768 以上,推荐浏览器 Chrome、Edge 等现代浏览器,截止 2021 年 12 月 5 日的访问次数:1872 万 9823 站长邮箱

沪 ICP 备 18037240 号-1

沪公网安备 31011002002865 号