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

HTML5 2D 游戏开发 设置舞台(2)启动游戏

HTML5 2D 游戏开发 设置舞台(2)启动游戏

启动游戏SnailBait 的全局对象如   和   所示,Snail Bait 只有两个全局对象:SnailBait 函数和 snailBait 对象。

清单 3 显示了启动游戏的 JavaScript。该清单的开头定义了三个 SnailBait 方法的实现:animate()、start() 和 initializeImages()。
清单 3. 启动
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
35
36
37
38
39
40
41
42
SnailBait.prototype = {
   ...

   // The 'this' variable in the animate() method is
   // the window object, so the method uses snailBait instead

   animate: function (now) {
      snailBait.fps = snailBait.calculateFps(now);
      snailBait.draw(now);

      requestNextAnimationFrame(snailBait.animate);
   },

   start: function () {
      this.turnRight();                     // Sets everything in motion
      this.splashToast('Good Luck!', 2000); // "Good Luck" is displayed for 2 seconds

      requestNextAnimationFrame(this.animate);
   },

   initializeImages: function () {
      this.background.src = 'images/background_level_one_dark_red.png';
      this.runnerImage.src = 'images/runner.png';
   
      this.background.onload = function (e) {

         // ...the 'this' variable is the window object,
         // so this function uses snailBait instead.
      
         snailBait.start();
      };
   },
}; // End of SnailBait.prototype


// Launch game

var snailBait = new SnailBait(); // Note: By convention, the object
                                     // reference starts with lowercase, but
                                     // the function name starts with uppercase

snailBait.initializeImages();




JavaScript 的挑剔的  对象如果您曾使用过经典的面向对象的语言(如 Java),那么您应该预料到,某个对象的 this 变量总是指向与方法相关联的对象。
JavaScript 最麻烦的一件事情是,this 变量是变化的。在清单 2 中,animate() 方法和背景图像的 onload 事件处理器中的 this 变量涉及 window 对象,而不是 snailBait 对象,所以这些方法可以直接访问 snailBait 对象。

  中的 JavaScript 实例化一个 SnailBait 对象,并调用了它的 initializeImages() 方法,该方法实现背景图像的 onload 事件处理器。当图像加载时,该事件处理器调用了 start() 方法。
start() 方法调用 turnRight(),它设置移动中的背景和平台。还调用了 splashToast(),以显示 Good Luck! 两秒。最后,start() 调用了 requestNextAnimationFrame() polyfill(我们曾在本系列第二期文章中讨论过它,请参阅那篇文章的   部分),它最终调用该游戏的 animate() 方法。
animate() 方法将绘制当前帧,然后调用 requestNextAnimationFrame()(指定它本身作为回调函数)来保持动画。
这就是游戏开始的方式。接下来,我将告诉您在开始游戏之后如何暂停它。
返回列表