HTML and CSS Reference
In-Depth Information
One option is to make a copy of the list of objects at the beginning of each frame, but this could get costly to
do each frame. The best solution is to first mark objects for removal in a separate array and then actually remove
them from the object list after every object has had its turn. Following is the solution
GameBoard
uses:
// Mark an object for removal
this.remove = function(obj) {
var wasStillAlive = this.removed.indexOf(obj) != -1;
if(wasStillAlive) { this.removed.push(obj); }
return wasStillAlive;
};
// Reset the list of removed objects
this.resetRemoved = function() { this.removed = []; }
// Remove objects marked for removal from the list
this.finalizeRemoved = function() {
for(var i=0,len=this.removed.length;i<len;i++) {
var idx = this.objects.indexOf(this.removed[i]);
if(idx != -1) {
this.cnt[this.removed[i].type]--;
this.objects.splice(idx,1);
}
}
}
At the beginning of each step,
resetRemoved
is called to reset the list of objects to be removed. The re-
move method first checks if an object has already been removed and then adds it to the list of objects to remove
only if it's not already there. It then returns
true
if the object was added or
false
if the object was already
dead. After every object has its turn,
finalizeRemoved
is called. This method finds the removed objects in
the objects list using
Array.indexOf
and then uses the
Array.splice
method to cut those objects out of
the list. When an object is removed from the list, it is effectively dead because it no longer has its
step
and
draw
methods called.
Iterating over the List of Objects
Because much of what
GameBoard
does is iterate over a list of objects, it stands to reason that a couple of
helper methods to make that easier would come in handy. Two main methods are needed. First, a simple iterate
method that calls the same function on every object in the object list is useful for the
step
and
draw
methods.
Second, a
detect
method that returns the first object for which a passed-in function returns
true
makes col-
lision detection easier. Both of these methods are listed here:
First up is
iterate
:
// Call the same method on all current objects
this.iterate = function(funcName) {
var args = Array.prototype.slice.call(arguments,1);
for(var i=0,len=this.objects.length;i<len;i++) {
var obj = this.objects[i];