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

HTML5 2D 游戏开发 结束游戏(3)保留得分

HTML5 2D 游戏开发 结束游戏(3)保留得分

保留得分从本系列的 开始,Snail Bait 一直有一个处于非工作状态的计分板。现在是时候让其发挥计分板的功效了。第一步是为某些类型的 sprite 分配一些值。例如,清单 5 显示了该游戏的 createRubySprites() 方法,为每个红宝石分配了一个 100 点的值:
清单 5. 分配 sprite 值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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(this.RUBY_SPARKLE_DURATION,
                                         this.RUBY_SPARKLE_INTERVAL),
                    new BounceBehavior(800, 600, 120) ]);

        ruby.width = this.RUBY_CELLS_WIDTH;
        ruby.height = this.RUBY_CELLS_HEIGHT;
         
        ruby.value = 100;

        this.rubies.push(ruby);
     }
  },
  ...
};




如 所示,当跑步小人与其他具有某个值的 sprite 发生碰撞时,碰撞行为的 adjustScore() 方法就会调整游戏得分,并更新 HTML score 元素。清单 6 显示了 adjustScore() 方法:
清单 6. 碰撞后调整得分
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var SnailBait = function () {
  ...
  // The collide behavior is attached to the runner

  this.collideBehavior = {
     ...
     adjustScore: function (otherSprite) {
        if (otherSprite.value) {
           snailBait.score += otherSprite.value;
           snailBait.score = snailBait.score < 0 ? 0 : snailBait.score;
           snailBait.scoreElement.innerHTML = snailBait.score;
        }
     },
     ...
  }
};

返回列表