本文由
伯乐在线 -杨帅 翻译自
lessmilk。未经许可,禁止转载!
欢迎加入:技术翻译小组,或分享原创到伯乐头条。
在上一篇HTML5教程中,我们做了一个简化版的Flappy Bird。虽然可以“称得上”是一款游戏了,但却是一款很无聊的游戏。在这篇文章中我们来看一看如何给它添加动画效果和音效。虽然并没有改变游戏的机制,但却能够使游戏变得更加有趣。你可以点击这里先体验一下。
设置
首先下载新的模板。其中包括了我们在上一个教程中完成的代码和一个新的音效文件。
打开main.js,开始敲吧。
添加飞行动画
小鸟上下飞行的方式太单调了,我们来加一些特效,让它看起来有点儿游戏的样子。
1.下降时角度转动速度放慢,直到特定值。
2.上升时翻转角度。
第一个任务很简单,我们只需要添加两行代码到update()方法。
1
2
|
if
this.bird.angle += 1; |
第二步我们有两个选择,
简单起见,我们可以只在jump()方法中添加
1
|
this.bird.angle = -20; |
但是这中角度的骤变看起来有点儿别扭。所以,我们还可以让角度有个变化的过程。我们可以用如下代码替换掉上面的。
1
2
3
4
5
6
7
8
|
//
var animation = this.game.add.tween(this.bird); //
in 100 milliseconds animation.to({angle: -20}, 100); //
animation.start(); |
也可以揉成一行代码:
1
|
this.game.add.tween(this.bird).to({angle: -20}, 100).start(); |
这样一来就差不多了,如果你现在测试一下游戏,你会发现小鸟的角度变化得并不自然。像左边的图,但是我们想要的是右图的效果。
为了达到这个目的,我们要做的是改变小鸟的中心(anchor)。在create()方法中添加如下代码来改变中心(anchor)。
1
|
this.bird.anchor.setTo(-0.2, 0.5); |
现在测试一下游戏你就会发现已经好得多了。
添加失败动画
首先,更新update()方法:用hit_pipe()替换restart_rame()。
1
|
this.game.physics.overlap(this.bird, this.pipes, this.hit_pipe, null, this); |
然后我们来写一个hit_pipe()方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
hit_pipe: function () { // If the bird has already hit a pipe, we have nothing to do if (this.bird.alive == false ) return ; // Set the alive property of the bird to false this.bird.alive = false ; // Prevent new pipes from appearing this.game. time .events.remove(this.timer); // Go through all the pipes, and stop their movement this.pipes.forEachAlive( function (p){ p.body.velocity.x = 0; }, this); }, |
最后,为了保证撞了管子的小鸟不诈尸,在jump()方法的最前面添加如下代码:
1
2
|
if
false ) return ; |
动画效果添加完毕。
添加音效
用Phaser添加音效非常容易。
(作者提供的音效文件貌似无法播放,大家可以找点儿别的代替。)
在preload()中添加
1
|
this.game.load.audio( 'jump' , 'assets/jump.wav' ); |
在create()中添加
1
|
this.jump_sound = this.game.add.audio( 'jump' ); |
最后在jump()中添加
1
|
this.jump_sound.play(); |
来实现跳跃音效的调用。
最终效果的源码可以点击这里下载
最后附上译者Flappy Bird纪录,求超越。