模拟蛇的移动
原文地址: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