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

HTML5 2D 游戏开发 碰撞检测和 sprite 动画(5)处理碰撞

HTML5 2D 游戏开发 碰撞检测和 sprite 动画(5)处理碰撞

处理碰撞检测到碰撞后,必须对它们进行处理。Snail Bait 的 processCollision() 用于处理跑步小人与其他 sprite 之间的碰撞,这从 清单 9 中可以看到。
清单 9. 处理碰撞:processCollision()
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 () {
   processCollision: function (sprite, otherSprite) {
      if ('coin'  === otherSprite.type    ||  // bad guys
          'sapphire' === otherSprite.type ||
          'ruby' === otherSprite.type     ||
          'button' === otherSprite.type   ||
          'snail bomb' === otherSprite.type) {
         otherSprite.visible = false;
      }

      if ('bat' === otherSprite.type   ||  // good guys
          'bee' === otherSprite.type   ||
          'snail' === otherSprite.type ||
          'snail bomb' === otherSprite.type) {
         snailBait.explode(sprite);
      }

      if (sprite.jumping && 'platform' === otherSprite.type) {
         this.processPlatformCollisionDuringJump(sprite, otherSprite);
      }
   },
   ...
};




当跑步小人与好的东西(金币、蓝宝石、红宝石和纽扣)或与蜗牛炸弹碰撞时,Snail Bait 会让另一个 sprite 消失不见,将它的 visible 属性设置为 false。
当跑步小人与坏东西(蝙蝠、蜜蜂、蜗牛和蜗牛炸弹)碰撞时,processCollision() 使用 Snail Bait 的 explode() 方法让跑步小人爆炸。目前,explode() 方法简单地将 BOOM 打印到控制台。本系列的下一篇文章将讨论 explode() 方法的最终实现。
最后,清单 10 中的 processPlatformCollisionDuringJump() 方法在跑步小人跳跃时处理平台碰撞。
清单 10. processPlatformCollisionDuringJump()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
processPlatformCollisionDuringJump: function (sprite, platform) {
      var isDescending = sprite.descendAnimationTimer.isRunning();
   
      sprite.stopJumping();
   
      if (isDescending) { // Collided with platform while descending
         // land on platform

         sprite.track = platform.track;
         sprite.top = snailBait.calculatePlatformTop(sprite.track) - sprite.height;
      }
      else { // Collided with platform while ascending
         sprite.fall();
      }
   }
};




当跑步小人在跳跃时与一个平台碰撞的时候,如果她处于跳跃的下降阶段,她会停止跳跃并落在平台上。如果跑步小人正在上升,她从下面与平台碰撞,那么她会降落。现在,跑步小人的 fall() 方法的实现如 清单 11 中所示。
清单 11. 用于下降的 Stopgap 方法
1
2
3
4
5
6
7
8
9
10
11
12
var SnailBait =  function () {

   ...


   this.runner.fall = function () {
      snailBait.runner.track = 1;
      snailBait.runner.top = snailBait.calculatePlatformTop(snailBait.runner.track) -
                             snailBait.runner.height;
   };
   ...
};




跑步小人的 fall() 方法直接将跑步小人放在底部轨道上,即最矮的平台上。在本系列的下一篇文章中,您将了解如何使用逼真的下落来重新实现该方法,并考虑重力因素。
返回列表