HTML and CSS Reference
In-Depth Information
if(gridmaxX >= this.numXTiles) gridmaxX = this.numXTiles-1;
if(gridmaxY >= this.numYTiles) gridmaxY = this.numYTiles-1;
for(var y = gridminY; y <=gridmaxY; y++)
var idx = y*this.numXTiles;
for(var x = gridminX; x <=gridmaxX; x++)
This makes finding entities extremely quick, because you've already pre-sorted the environment. When a
mouse-click comes in, you simply find the bucket it resides in, and return the list of entities for that bucket, which
you've already calculated.
var gridminX = Math.floor(x / this.tileSize);
var gridminY = Math.floor(y / this.tileSize);
var idx = gridminX + gridminY*this.numXTiles;
var ents = this.tileData[idx];
return ents;
This makes modification to your existing code very nice and tidy:
function findClickedSprite(x,y)
//loop through all target sprites
var tgtents = acclGrid.getEntsForPoint(x,y);
for(var i =0; i < tgtents .length; i++)
var sp = tgtents [i];
//pick is not intersecting with this sprite
if( x < sp.pos.x || x > sp.pos.x + sp.size.w || y < sp.pos.y || y > sp.pos.y + sp.size.h)
return sp;
return null;
The acceleration grid reduces performance overhead by reducing the number of times the inner loop is called;
regardless of how many sprites you have universally, this bucketing will only care about what sprites reside in a grid
cell. An easy trade-off in bang-for-the-buck; you didn't have to derail yourself by worrying how JavaScript is handling
the math for convex hulls or the array-access times for pixel-perfect picking (both covered later in this chapter). It's a
simple technique that can be used for static and dynamic environments.
Note that to use the grid, an entity needs to be responsible for updating its markings on the grid. For your simple
purpose, you only need to update the entity spawning code to mark the location of the object in the grid (see Listing 5-9).
Search WWH ::

Custom Search