日期:2014-05-16 浏览次数:21063 次
首先是素材
demo地址:
http://jsfiddle.net/DUN2Y/
首先Phaser 是一个基于canvas的 javascript游戏引擎,说白了就是一个框架,让你不用自己写 canvas的方法来实现动画效果。
官网地址:www.phaser.io
一下采用最新版2.0
var game = new Phaser.Game(800, 600, Phaser.CANVAS, '', { preload: preload, create: create, update: update,render:render });
中间这个空字符串代表canvas的ID,也就是如果你自定义一个id为aaa的canvas,这一项就可以写aaa,否则,会默认在body建立canvas。
最后的四个参数,很好理解,就是整个游戏的方法,载入前,创建,更新方法,下面详细介绍每个方法。
function preload() { game.load.image('sky', 'assets/sky.png'); game.load.image('ground', 'assets/platform.png'); game.load.image('star', 'assets/star.png'); game.load.spritesheet('dude', 'assets/dude.png', 32, 48); }
function create() { //把canvas的 边界设置成实物,也就是,可以用来检测碰撞和覆盖的实物 game.physics.setBoundsToWorld(); game.add.sprite(0, 0, 'sky'); // 创建一组组件,其中可以把一些用处相同的组件放在一个grope里,便于管理 platforms = game.add.group(); //允许组件设定重力方面的配置 platforms.enableBody = true; //重力类型为arcade platforms.physicsBodyType = Phaser.Physics.ARCADE; // 创建地板 var ground = platforms.create(0, game.world.height - 64, 'ground'); // 缩放地板,使其自适应canvas大小 ground.scale.setTo(2, 2); // 当地板被碰撞时,固定它的位置 ground.body.immovable = true; // 创建两个台阶 var ledge = platforms.create(400, 400, 'ground'); ledge.body.immovable = true; ledge = platforms.create(-150, 250, 'ground'); ledge.body.immovable = true; //ledge2.body.setPolygon(62,112, 100,120,88,40); //创建小人 player = game.add.sprite(32, game.world.height - 450, 'dude'); game.physics.enable(player, Phaser.Physics.ARCADE); console.log(player.body); //弹性指数 player.body.bounce.y = 0.6; //重力指数 player.body.gravity.y = 400; //是否允许和canvas边界碰撞 player.body.collideWorldBounds = true; //添加动画 player.animations.add('left', [0, 1, 2, 3], 10, true); player.animations.add('right', [5, 6, 7, 8], 10, true); stars = game.add.group(); stars.enableBody = true; stars.physicsBodyType = Phaser.Physics.ARCADE; for (var i = 0 ; i < 12 ; i++) { var star = stars.create(i * 70, 0, "star"); star.body.gravity.y = 400; star.body.bounce.y = 0.7 + Math.random() * 0.2; star.body.collideWorldBounds = true; } cursors = game.input.keyboard.createCursorKeys(); score = game.add.text(12, 12, "score:"+scoreCount+"",{color:"#000"}); //var tilemap = game.add.tilemap("star",44,44,44,44); }
key为proload方法引入时为其分配的id也就是dude
这个方法为游戏添加一个精灵元素,精灵元素可以绑定事件,而且可以设置重力,弹性等参数,是框架里最常用的元素。
function update() { game.physics.arcade.collide(player, platforms); game.physics.arcade.collide(stars, platforms); game.physics.arcade.collide(player, ledge2); game.physics.arcade.overlap(player, stars, function(player, star){ console.log(stars.total); star.kill(); scoreCount++; score.text = "score:"+scoreCount+""; if (stars.total == 0) { alert(&quo