Sprite与组之间的处理

原文地址:http://www.phaser.io/examples/v2/arcade-physics/custom-sprite-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.spritesheet('veggies', 'images/phaser/fruitnveg32wh37.png', 32, 32);

    }

    Vegetable = function (game) {

        frame = game.rnd.between(0, 35);

        //  不要包含辣椒(frame 17)
        if (frame === 17) {
            frame = 1;
        }

        var x = game.rnd.between(100, 770);
        var y = game.rnd.between(0, 570);

        Phaser.Image.call(this, game, x, y, 'veggies', frame);

    };

    Vegetable.prototype = Object.create(Phaser.Image.prototype);
    Vegetable.prototype.constructor = Vegetable;

    Chilli = function (game) {

        var x = game.rnd.between(100, 770);
        var y = game.rnd.between(0, 570);

        Phaser.Sprite.call(this, game, x, y, 'veggies', 17);

        game.physics.arcade.enable(this);

    };

    Chilli.prototype = Object.create(Phaser.Sprite.prototype);
    Chilli.prototype.constructor = Chilli;

    var sprite;
    var group;
    var cursors;

    function create() {

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

        game.stage.backgroundColor = '#2d2d2d';

        //  本例展示了如何检测Sprite和组之间的碰撞

        group = game.add.group();

        for (var i = 0; i < 70; i++) {
            if (i < 50) {
                //  蔬菜组没有物理效果
                group.add(new Vegetable(game));
            }
            else {
                //  辣椒组有物理效果
                group.add(new Chilli(game));
            }
        }

        //  我们控制的角色
        sprite = game.add.sprite(32, 200, 'phaser');

        game.physics.arcade.enable(sprite);

        cursors = game.input.keyboard.createCursorKeys();

    }

    function update() {

        game.physics.arcade.overlap(sprite, group, collisionHandler, null, this);

        sprite.body.velocity.x = 0;
        sprite.body.velocity.y = 0;

        if (cursors.left.isDown) {
            sprite.body.velocity.x = -200;
        }
        else if (cursors.right.isDown) {
            sprite.body.velocity.x = 200;
        }

        if (cursors.up.isDown) {
            sprite.body.velocity.y = -200;
        }
        else if (cursors.down.isDown) {
            sprite.body.velocity.y = 200;
        }

    }

    function collisionHandler(player, chilli) {

        //  如果玩家与辣椒发生碰撞,则可以“吃”掉它
        chilli.kill();

    }
}

发布时间:2016/11/20 21:55:04  阅读次数:4165

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

沪ICP备18037240号-1

沪公网安备 31011002002865号