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

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;
}
},
...
}
};
|
|
|
|
|
|
|