HTML and CSS Reference
In-Depth Information
// Draw all the objects
this.draw= function(ctx) {
this.iterate('draw',ctx);
};
Both step and draw use the iterate method to call a specifically named function on each object in the
list, with step also making sure to reset and finalize the list of removed items.
Handling Collisions
The last bit of functionality in the purview of GameBoard is the handling of collisions. Alien Invasion uses a
simplified collision model that reduces each of the sprites on the board to a simple rectangular bounding box. If
the bounding boxes of two different objects overlap, then those two sprites are deemed to be colliding. Because
each sprite has an x and a y position in addition to a width and a height, this box is easy to calculate.
NOTE A bounding box is the smallest rectangle that encompasses the entirety of an object. Using bound-
ing boxes to do collision detection instead of polygons or exact pixel data is faster to calculate, but is much
less accurate.
GameBoard uses two functions to handle collision detection. The first, overlap , simply checks for the
overlap between two objects' bounding boxes and returns true if they intersect. The easiest way to do this
detection is clever. Rather than check whether one object is in the other, you simply need to check if one object
couldn't be in the other and negate the result.
this.overlap = function(o1,o2) {
return !((o1.y+o1.h-1<o2.y) || (o1.y>o2.y+o2.h-1) ||
(o1.x+o1.w-1<o2.x) || (o1.x>o2.x+o2.w-1));
};
What's going on here is that the bottom edge of object one is checked against the bottom edge of object two
to see if object one is to the right of object two. Next, the top edge of object one is checked against the bottom
edge of object two and so on through each of the corresponding edges. If any of these are true, you know object
one doesn't overlap object two. By simply negating the result of this detection, you can tell if the two objects
overlap.
With a function in your pocket to determine overlap, it becomes easy to check one object against all the other
objects in the list.
this.collide = function(obj,type) {
return this.detect(function() {
if(obj != this) {
var col = (!type || this.type & type) && board.overlap(obj,this)
return col ? this : false;
}
});
};
Collide uses the detect function to match the passed-in object against all the other objects and returns
the first object for which overlap returns true . The only complication is the support for an optional type para-
meter. The idea behind this is that different types of objects want to collide with only certain objects. Enemies,
 
Search WWH ::




Custom Search