HTML and CSS Reference
In-Depth Information
Figure 5-2. Given a 2D grid, you can determine what sprites overlap with what cells. Later, when a pick event occurs,
you can determine what cell the point resides in, and reduce the number of per-sprite checks you need to perform
Your BucketGrid class will effectively create a 2D array of arrays , such that when a sprite is spawned, you
calculate what grid cells it overlaps, and add a pointer to this instance to each of those cell's lists; see Listing 5-7.
Listing 5-7. Definition of a BucketGrid
function BucketGrid(){
this.tileSize=32;
this.numXTiles=0;
this.numYTiles=0;
this.tileData=null;
this.init=function()
{
this.tileData = new Array();
this.tileSize = 16;
this.numXTiles= 512/this.tileSize;
this.numYTiles= 512/this.tileSize;
this.tileData.length = this.numXTiles*this.numYTiles;
for(var k =0; k < this.tileData.length;k++)
this.tileData[k] = new Array();
}
Marking a sprite instance on the grid is pretty simple. You just run some math on the corners of the sprite to
calculate the min/max boundaries of it, and what tiles those boundaries fall into; and for each grid cell, you add the
sprite to the containing list (see Listing 5-8).
Listing 5-8. Given a sprite, mark which grid cells it overlaps in
this.markInstanceInAccelGrid=function(sp)
{
var gridminX = Math.floor(sp.pos.x / this.tileSize);
var gridmaxX = Math.floor((sp.pos.x + sp.size.w) / this.tileSize);
var gridminY = Math.floor(sp.pos.y / this.tileSize);
var gridmaxY = Math.floor((sp.pos.y + sp.size.h) / this.tileSize);
 
Search WWH ::




Custom Search