模拟蛇的移动

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

效果

源代码

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('ball', 'images/phaser/shinyball.png');

    }

    var snakeHead; //蛇头
    var snakeSection = new Array(); // sprite数组构成蛇身
    var snakePath = new Array(); // 位置数组用来存储蛇身的跟随位置
    var numSnakeSections = 30; // 蛇身的关节数量
    var snakeSpacer = 6; // 关节的间隙大小

    function create() {

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

        game.world.setBounds(0, 0, 800, 600);

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

        snakeHead = game.add.sprite(400, 300, 'ball');
        snakeHead.anchor.setTo(0.5, 0.5);

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

        //  初始化蛇身数组
        for (var i = 1; i <= numSnakeSections - 1; i++) {
            snakeSection[i] = game.add.sprite(400, 300, 'ball');
            snakeSection[i].anchor.setTo(0.5, 0.5);
        }

        //  初始化蛇身关节位置信息数组
        for (var i = 0; i <= numSnakeSections * snakeSpacer; i++) {
            snakePath[i] = new Phaser.Point(400, 300);
        }

    }

    function update() {

        snakeHead.body.velocity.setTo(0, 0);
        snakeHead.body.angularVelocity = 0;

        if (cursors.up.isDown) {
            snakeHead.body.velocity.copyFrom(game.physics.arcade.velocityFromAngle(snakeHead.angle, 300));

            // 当蛇头移动时,就在位置数组中插入新的位置,并舍弃最后数组中一个数据 
            // and knock the last position off the end

            var part = snakePath.pop();

            part.setTo(snakeHead.x, snakeHead.y);

            snakePath.unshift(part);

            for (var i = 1; i <= numSnakeSections - 1; i++) {
                snakeSection[i].x = (snakePath[i * snakeSpacer]).x;
                snakeSection[i].y = (snakePath[i * snakeSpacer]).y;
            }
        }

        if (cursors.left.isDown) {
            snakeHead.body.angularVelocity = -300;
        }
        else if (cursors.right.isDown) {
            snakeHead.body.angularVelocity = 300;
        }

    }

    function render() {

        game.debug.spriteInfo(snakeHead, 32, 32);

    }
}

发布时间:2016/11/27 下午10:37:13  阅读次数:4453

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

沪 ICP 备 18037240 号-1

沪公网安备 31011002002865 号