HTML and CSS Reference
In-Depth Information
The cloning is slightly more complicated than it seems because JavaScript doesn't have a built-in mechanism
for deep cloning a list of objects inside an Array . To get around this, each entry in the level data is looped
over and the built-in Object.create method is called to create a new object with the existing data as the
prototype. That new object is then pushed onto a new Array .
Next is the meat of the Level object, the step method. Even though Level isn't a normal Sprite , it's
going to pretend it is and behave like one by responding to the step and draw methods. The step method in
Listing 2-15 has the responsibility to keep track of the current time and dropping enemies onto the page in se-
quence.
Listing 2-15: Level Step Method
Level.prototype.step = function(dt) {
var idx = 0, remove = [], curShip = null;
// Update the current time offset
this.t += dt * 1000;
// Example levelData
// Start, End, Gap, Type, Override
// [[ 0, 4000, 500, 'step', { x: 100 } ]
while((curShip = this.levelData[idx]) &&
(curShip[0] < this.t + 2000)) {
// Check if past the end time
if(this.t > curShip[1]) {
// If so, remove the entry
remove.push(curShip);
} else if(curShip[0] < this.t) {
// Get the enemy definition blueprint
var enemy = enemies[curShip[3]],
override = curShip[4];
// Add a new enemy with the blueprint and override
this.board.add(new Enemy(enemy,override));
// Increment the start time by the gap
curShip[0] += curShip[2];
}
idx++;
}
// Remove any objects from the levelData that have passed
for(var i=0,len=remove.length;i<len;i++) {
var idx = this.levelData.indexOf(remove[i]);
if(idx != -1) this.levelData.splice(idx,1);
}
// If there are no more enemies on the board or in
// levelData, this level is done
if(this.levelData.length == 0 && this.board.cnt[OBJECT_ENEMY] == 0) {
 
 
Search WWH ::




Custom Search