首页 | 新闻 | 新品 | 文库 | 方案 | 视频 | 下载 | 商城 | 开发板 | 数据中心 | 座谈新版 | 培训 | 工具 | 博客 | 论坛 | 百科 | GEC | 活动 | 主题月 | 电子展
返回列表 回复 发帖

HTML5 2D 游戏开发 操纵时间,第 1 部分(2)将跳跃责任移交给跑步小人

HTML5 2D 游戏开发 操纵时间,第 1 部分(2)将跳跃责任移交给跑步小人

将跳跃责任移交给跑步小人清单 3 显示了一个重构的窗口 onkeydown 事件处理程序实现,该实现比  中的实现更简单,它将跳跃责任从事件处理程序移交给跑步小人。
清单 3. 窗口的关键处理程序委托给跑步小人
1
2
3
4
5
6
7
8
window.onkeydown = function (e) {
   var key = e.keyCode;
   ...
   
   if (key === 74) { // 'j'
      runner.jump();
   }
};




启动游戏时,Snail Bait 调用了一个方法 equipRunner(),如清单 4 所示:
清单 4. 在游戏启动时装备跑步小人
1
2
3
4
5
6
7
8
9
SnailBait.prototype = {
   ...
   start: function () {
      this.createSprites();
      this.initializeImages();
      this.equipRunner();
      this.splashToast('Good Luck!');
   },
};




如清单 5 所示,equipRunner() 方法为跑步小人添加了属性和 jump() 方法:
清单 5. 装备跑步小人:跑步小人的 jump() 方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
SnailBait.prototype = {
   equipRunner: function () {
      // This function sets runner attributes:

      this.runner.jumping = false; // 'this' is snailBait
      this.runner.track = this.INITIAL_RUNNER_TRACK;

      ... // More runner attributes omitted for brevity

      // This function also implements the runner's jump() method:

      this.runner.jump = function () {
         if ( ! this.jumping) {    // 'this' is the runner.
            this.jumping = true; // Start the jump
         }
      };
   },
},




视图和控件跑步小人的跳跃行为及其相应的 jump() 方法类似于一个视图/控件对。Snail Bait 在跑步小人跳跃时绘制跑步小人的方式是在行为中实现的,反之,跑步小人的 jump() 方法充当了一个简单控制器,控制跑步小人目前是否跳跃。

此外,跑步小人也有属性呈现其当前踪迹以及是否正在跳动。
如果跑步小人目前没有跳动,runner.jump() 将其 jumping 属性设置为 true。Snail Bait 在单独的行为对象中实现跳跃操作,就像实现跑步小人的其他行为一样,比如跑步和降落,事实上,所有 sprite 行为都是这样实现的。Snail Bait 在创建跑步小人时会将对象添加到其行为数组中,如清单 6 所示:
清单 6. 创建跑步小人及其行为
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var SnailBait = function () {
   ...
   this.jumpBehavior = {
      execute: function(sprite, time, fps) {

         // Implement jumping here

      },
      ...
   };
   ...

   this.runner = new Sprite('runner',          // type
                            this.runnerArtist,  // artist
                            [ this.runBehavior, // behaviors
                              this.jumpBehavior,
                              this.fallBehavior
                            ]);
   ...
};




现在基础架构已经为初始化跳跃活动做好准备,我可以将全部精力集中在跳跃行为上了。
返回列表