HTML5 2D 游戏开发 操纵时间,第 1 部分(4)细化跳跃行为
 
- UID
- 1066743
|

HTML5 2D 游戏开发 操纵时间,第 1 部分(4)细化跳跃行为
细化跳跃行为现在已经有了秒表,让我们使用它来细化跳跃行为。首先,修改 中的 equipRunner() 方法,如清单 9 所示:
清单 9. 修改后的equipRunner() 方法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
27
28
29
30
31
32
33
34
| SnailBait.prototype = {
...
this.RUNNER_JUMP_HEIGHT = 120, // pixels
this.RUNNER_JUMP_DURATION = 1000, // milliseconds
equipRunnerForJumping: function () {
this.runner.JUMP_HEIGHT = this.RUNNER_JUMP_HEIGHT;
this.runner.JUMP_DURATION = this.RUNNER_JUMP_DURATION;
this.runner.jumping = false;
this.runner.ascendStopwatch = new Stopwatch(this.runner.JUMP_DURATION/2);
this.runner.descendStopwatch = new Stopwatch(this.runner.JUMP_DURATION/2);
this.runner.jump = function () {
if (this.jumping) // 'this' is the runner
return;
this.jumping = true;
this.runAnimationRate = 0; // Freeze the runner while jumping
this.verticalLaunchPosition = this.top;
this.ascendStopwatch.start();
};
},
equipRunner: function () {
...
this.equipRunnerForJumping();
},
...
};
|
修改后的 equipRunner() 实现调用了一个新方法:equipRunnerForJumping()。顾名思义,该方法为跑步小人装备了跳跃行为。该方法创建了两个秒表:runner.ascendStopwatch 用于上升,runner.descendStopwatch 用于下落。
跳跃开始时,jump() 方法启动跑步小人的上升秒表,正如您在 中所看到的。该方法还将跑步小人的跑步动画速度(通过其跑动动画定义了跑步小人的速度有多快)设置为零,让跑步小人停止跑步,此时跑步小人在空中。run() 方法还记录了跑步小人的垂直位置,以便在跳跃完成时让其返回原地。
表 1 对 中设置的所有跑步者属性进行了总结:
表 1. 跑步小人与相关的属性属性描述JUMP_DURATION一个常量,表示跳跃持续的时间:1000 毫秒。JUMP_HEIGHT一个常量,代表跳跃高度:120 像素。跳跃的最高点距下一个轨道 20 像素。ascendStopwatch记录跑步小人在跳跃过程中所用的上升时间的秒表。descendStopwatch记录跑步小人在跳跃过程中所用的下落时间的秒表。jumpApex跑步小人跳跃的最高点;跳跃行为使用 apex 确定在下落过程中跑步小人在每个框架中所用的下落空间。jumping一个标记,跑步小人跳跃时其值为 true。verticalLaunchPosition跳跃开始时,跑步小人的位置(跑步小人 sprite 的左上角)。完成跳跃后返回该位置。
接着,我将在清单 10 中重构最初在 中实现的跳跃行为:
清单 10. 跳跃行为,重新修改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
| var SnailBait = function () {
this.jumpBehavior = {
...
execute: function(sprite, context, time, fps) {
if ( ! sprite.jumping) {
return;
}
if (this.isJumpOver(sprite)) {
sprite.jumping = false;
return;
}
if (this.isAscending(sprite)) {
if ( ! this.isDoneAscending(sprite)) this.ascend(sprite);
else this.finishAscent(sprite);
}
else if (this.isDescending(sprite)) {
if ( ! this.isDoneDescending(sprite)) this.descend(sprite);
else this.finishDescent(sprite);
}
}
},
...
|
中的跳跃行为是一个高级别抽象的实现,它将跳跃细节留给另一个方法,比如 ascend() 和 isDescending()。现在需要做的就是填充细节,通过使用跑步小人的上升和下降秒表来实现以下方法:
- isJumpOver()
- ascend()
- isAscending()
- isDoneAscending()
- finishAscent()
- descend()
- isDescending()
- isDoneDescending()
- finishDescent()
|
|
|
|
|
|