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

HTML5 2D 游戏开发 实现 Sprite 行为(4)非游戏独有的行为

HTML5 2D 游戏开发 实现 Sprite 行为(4)非游戏独有的行为

非游戏独有的行为轻量型行为和状态paceBehavior 可用作一个轻量型行为,因为它是无状态的。它没有状态是因为它将状态(每个 sprite 的位置和方向)存储在 sprite 自身中。

我们在本文中讨论的第一个行为( runBehavior )是一种有状态行为,它与一个 sprite 紧密关联。接下来要讨论的 paceBehavior 是一个无状态行为,该行为与各个 sprite 是分离开的,所以一个实例可供多个 sprite 使用。
行为可进一步一般化:不仅可以将它们与各个 sprite 分离,还可以将它们与游戏本身分离。Snail Bait 使用了 3 种可用在任何游戏中使用的行为:
  • bounceBehavior
  • cycleBehavior
  • pulseBehavior
弹跳行为上下弹跳一个 sprite,这个周期性的行为循环显示 sprite 的一组图像,心跳行为操纵了 sprite 的不透明度,使它显示为好像是 sprite 正在心跳。
弹跳和心跳行为都涉及到非线性动画,我将在未来的文章中探讨这一主题。这个周期性行为线性循环显示了一个 sprite 的行为,所以我将使用该行为的实现来演示如何实现可在任何游戏中使用的行为。
闪耀的红宝石Snail Bait 的红宝石和蓝宝石会不停闪耀,如图 4 所示:
图 4. 闪耀的红宝石序列Snail Bait 的 sprite 表单包含红宝石和蓝宝石的图形序列;循环显示这些图像会带来闪耀的效果。
清单 8 给出了创建红宝石的 Snail Bait 方法。可以采用几乎相同的方法(未给出)创建蓝宝石。createRubySprites() 方法还创建一种每隔 500 毫秒显示红宝石闪耀序列中的下一个图像 100 毫秒的周期性行为。
清单 8. 创建红宝石
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
SnailBait.prototype = {
   ...
   createRubySprites: function () {
      var ruby,
          rubyArtist = new SpriteSheetArtist(this.spritesheet, this.rubyCells);
   
      for (var i = 0; i < this.rubyData.length; ++i) {
         ruby = new Sprite('ruby', rubyArtist,
                           [ new CycleBehavior(100,     // animation duration
                                                 500) ]); // interval between animations
         ...
      }
   },
   ...
};




清单 9 列出了这个周期性行为:
清单 9. CycleBehavior 行为
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
// This behavior advances the sprite artist through
// the sprite's images at a specified animation rate.

CycleBehavior = function (duration, interval) {
   this.duration = duration || 0;  //  milliseconds
   this.interval = interval || 0;
   this.lastAdvance = 0;
};

CycleBehavior.prototype = {
   execute: function(sprite, time, fps) {
      if (this.lastAdvance === 0) {
         this.lastAdvance = time;
      }

      // During the interval start advancing if the interval is over

      if (this.interval && sprite.artist.cellIndex === 0) {
         if (time - this.lastAdvance < this.interval) {
            sprite.artist.advance();
            this.lastAdvance = time;
         }
      }
      // Otherwise, if the behavior is cycling, advance if duration is over

      else if (time - this.lastAdvance > this.duration) {
         sprite.artist.advance();
         this.lastAdvance = time;
      }
   }
};




使行为一般化寻找机会让行为一般化,使它们可用在更多的环境中,这是一个不错的想法。

这个周期性行为将适用于任何一个具有 sprite 表单 artist 的 sprite,表明该行为不是 Snail Bait 所独有的,因此可在不同游戏中重用它。 中特定于 sprite 的跑动行为与  中非游戏特定的周期性行为具有很多共同点;事实上,周期性行为源于跑动行为。(跑动行为可能是一种更加一般化的周期性行为,但跑动行为还会考虑跑步小人的动画速率。)
返回列表