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

HTML5 2D 游戏开发 碰撞检测和 sprite 动画(2)Snail Bait 的碰撞检测

HTML5 2D 游戏开发 碰撞检测和 sprite 动画(2)Snail Bait 的碰撞检测

Snail Bait 的碰撞检测Snail Bait 的碰撞检测涉及到相对较大的 sprite 以较低的速度移动,所以该游戏使用边界框检测碰撞。这些边界框如 图 5 所示。
图 5. Snail Bait 的碰撞检测边界框 Snail Bait 将 sprite 活动(比如跑动、跳跃和爆炸)实现为 sprite 行为,请参阅文章 “ ”(developerWorks,2013 年 1 月),了解有关的更多信息。而且该游戏需要使用碰撞检测。在开发 Snail Bait 的时候,跑步小人有 3 种行为:她可以跑动、跳跃并与其他 sprite 碰撞。清单 1 给出了使用这 3 种行为来实例化跑步小人 sprite 的代码。
清单 1. 跑步小人的行为
1
2
3
4
5
6
7
8
9
Sprite = function () {
   ...
this.runner = new Sprite('runner',           // type
                            this.runnerArtist,  // artist
                            [ this.runBehavior, // behaviors
                              this.jumpBehavior,
                              this.collideBehavior
                            ]);
};




清单 2 给出了跑步小人的 collideBehavior 的代码。
清单 2. 跑步小人的碰撞行为
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
   var SnailBait =  function () {
   ...

   // Runner's collide behavior...............................................

   this.collideBehavior = {
      execute: function (sprite, time, fps, context) {  // sprite is the runner
         var otherSprite;

         for (var i=0; i < snailBait.sprites.length; ++i) {
            otherSprite = snailBait.sprites;

            if (this.isCandidateForCollision(sprite, otherSprite)) {
               if (this.didCollide(sprite, otherSprite, context)) {
                  this.processCollision(sprite, otherSprite);
               }
            }
         }
      },
      ...
      
   };
};




因为 collideBehavior 对象是一种 sprite 行为,所以 Snail Bait 对每个动画帧都调用了它的 execute() 方法。而且因为 collideBehavior 对象与跑步小人有关联,所以 Snail Bait 传递给 execute() 方法的 sprite 始终是跑步小人。请参阅文章 “实现 sprite 行为” 中的   一节,了解 sprite 行为的更多信息。
collideBehavior 对象的 execute() 方法封装了之前列出的  。最后 3 个步骤使用以下 collideBehavior 方法表示:
  • isCandidateForCollision(sprite, otherSprite)
  • didCollide(sprite, otherSprite, context)
  • processCollision(sprite, otherSprite)
以下各节将讨论每个方法的实现。
返回列表