【2Dhtml5游戏框架phaser介绍3】preload,create,update

来源:互联网 发布:matlab分水岭算法 编辑:程序博客网 时间:2024/05/21 06:01
使用phaser开发游戏,基本的结构如下:
var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update });


function preload() {
}


function create() {
}


function update() {
}


先声明一个Phaser.Game对象,第一个和第二个参数表示游戏大小,第三个参数表示渲染方式,有Phaser.CANVAS, Phaser.WEBGL,Phaser.AUTO三个选项,Phaser.CANVAS使用canvas来渲染,Phaser.WebGL使用WebGL使用来渲染,推荐使用Phaser.AUTO,框架会优先使用WebGL,如果浏览器不支持WebGL,则会用canvas来渲染。第四个参数指定这个游戏显示在哪个html标签里,比如页面有一个<div id='show'/>,第四个参数便可以为'show',游戏就会在这个div里显示。如果不写'',则自动追加到body里。第五个参数为一个对象,包含了phaser最基本的几个函数,这里写了3个最基本的,分别是preload,create,update。
preload里通常预加载一些游戏的资源文件,比如图片等,当一个phaser game开始运行时,会首先执行preload绑定的函数,凡是在这里定义的任何东西都会被加载,便于后面使用。


现在我们在function preload中加载一些资源,包括2个图片(图片都来源phaser官方的examples里):
function preload() {
  game.load.image('ship', 'assets/sprites/thrust_ship2.png');
  game.load.image('ground', 'assets/pics/platformer_backdrop.png');
}


使用game.load方法加载各种资源时,第一个参数为这个资源的引用名称,是一个唯一的id,在使用的时候就通过这个id来引用相应的资源。比如这里定义的ship,ground,使用ship时就可以引用到assets/sprites/thrust_ship2.png这个图片。


现在在function create中加入代码来让游戏运行起来:
function create() {
  game.add.sprite(0, 0, 'ground');
  game.add.sprite(0, 0, 'ship');

}

此时应该如下图


通过game.add.sprite()方法便会把在preload()中定义的资源显示在页面上,第一个参数是x坐标,第二个参数是y坐标,原点为左上角。注意显示的顺序为create中所写的顺序,也就是先显示ground,再显示ship,如果代码中先game.add.sprite(0, 0, 'ship'),再game.add.sprite(0, 0, 'ground'),当它们的坐标相同时,即都为(0,0)时,并且ground比ship大时,ship就会被遮住,无法看到。
现在我们在update()方法中加入代码,让飞船能通过键盘的方向键动起来。每当有键盘等触发或者刷新帧时,都会调用update定义的方法。此时所有的代码如下
<!doctype html><html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">    <head>        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">        <title>my ship</title>               <script src="_site/js/jquery-2.0.3.min.js" type="text/javascript"></script>                <script src="_site/js/phaser.js" type="text/javascript"></script><script>var game = new Phaser.Game(800, 600, Phaser.AUTO, 'example', { preload: preload, create: create, update: update });var ship;var cursors;function preload() {game.load.image('ship', 'assets/sprites/thrust_ship2.png');game.load.image('ground', 'assets/pics/platformer_backdrop.png');} function create() {game.add.sprite(0, 0, 'ground');ship = game.add.sprite(0, 0, 'ship');ship.anchor.set(0);game.physics.arcade.enable(ship);cursors = game.input.keyboard.createCursorKeys();} function update() {ship.body.velocity.x = 0;ship.body.velocity.y = 0;if (cursors.left.isDown){//  Move to the leftship.body.velocity.x = -150; ship.animations.play('left');}if (cursors.right.isDown){//  Move to the rightship.body.velocity.x = 150; ship.animations.play('right');}if (cursors.up.isDown){//  Move to the rightship.body.velocity.y = -150; ship.animations.play('up');}if (cursors.down.isDown){//  Move to the rightship.body.velocity.y = 150; ship.animations.play('down');}}</script>    </head>    <body>    <div id="example"></div>    </body></html>


0 0
原创粉丝点击