HTML5 2D 游戏开发 实现重力和添加声音(1)下落
 
- UID
- 1066743
|

HTML5 2D 游戏开发 实现重力和添加声音(1)下落
下落Snail Bait 的跑步者会在离开平台边缘或从下面碰撞平台时掉落,如图 1 所示:
图 1. 从平台边缘下落 跑步小人在一次跳跃的下降阶段末尾未落到平台上时也会下落,如图 2 所示:
图 2. 跳跃末尾的下落 跑步小人借助她的下落行为来下落。清单 1 显示了跑步小人 sprite 的实例化,指定了她的行为数组:
清单 1. 跑步小人的行为1
2
3
4
5
6
7
8
9
10
| Sprite = function () {
...
this.runner = new Sprite('runner', // type
this.runnerArtist, // artist
[ this.runBehavior, // behaviors
this.jumpBehavior,
this.collideBehavior,
this.fallBehavior,
]);
};
|
在跑步小人 sprite 可见时的每个动画帧中,Snail Bait 都会调用跑步小人的下落行为—就像 sprite 的所有行为一样。下落行为在大部分时间里都不会执行任何操作。当跑步小人的 falling 属性为 true 时,下落行为会递增式地在每个动画帧中垂直移动跑步小人,使她看起来正在下落。该属性由跑步小人的 fall() 方法设置,如清单 2 所示:
清单 2. 跑步小人的 fall()方法1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
| SnailBait.prototype = {
...
equipRunner: function () {
...
this.equipRunnerForJumping();
this.equipRunnerForFalling();
},
equipRunnerForFalling: function () {
...
this.runner.fallAnimationTimer = new AnimationTimer();
this.runner.fall= function (initialVelocity) {
// set attributes for the runner's fall behavior and
// start the fall animation timer
this.velocityY = initialVelocity || 0;
this.initialVelocityY = initialVelocity || 0;
this.falling = true;
this.fallAnimationTimer.start();
}
},
...
};
|
跑步小人的水平速度跑步小人下落行为的惟一的关注点是垂直放置跑步小人。下落行为不需要修改跑步小人的水平速度,因为尽管跑步小人看起来像是从右向左(或从左向右)运动,但她从未发生水平运动。相反,跑步小人下方的背景在移动,从而使她看起来是在水平运动。
当游戏开始时,Snail Bait 调用它的 equipRunner()方法,该方法包含跑步小人的跳跃和下落行为。equipRunnerForFalling()方法包含跑步小人的 fall() 方法的实现。跑步小人的 fall() 方法设置跑步小人的初始速度,将跑步小人的 falling 属性设置为 true ,并启动一个动画计时器来跟踪跑步小人下落期间经历了多少时间。
当跑步小人的 fall() 方法将跑步小人的 falling 属性设置为 true 时,它就会中止跑步小人的下落行为中的一个触发器。跑步小人然后开始下落,直到游戏将跑步小人的 falling 属性重置为 false 时为止。对重力的其余讨论将重点关注该行为的实现。 |
|
|
|
|
|