HTML and CSS Reference
In-Depth Information
Listing 5-9. Inserting the BucketGrid into the existing code
//--------------
var protoSprites = new Array();
var spriteInstances = new Array();
var acclGrid = new BucketGrid();
//--------------
function generateInstances()
{
acclGrid.init();
var numSprites = 4096; //magic number
for(var i = 0; i < numSprites; i++)
{
//.......
spriteInstances.push(sp);
acclGrid.markInstanceInAccelGrid(sp);
}
}
Caveats
This type of spatial acceleration structure is always in demand for games. It's primary goal is to reduce the number
of potential intersections to a defined list that is always smaller than the entire set. And to be clear, your BucketGrid
structure did nothing to increase the precision of your picking, but only increased the performance of your picking.
We will discuss precision issues more in the following sections.
One large issue to keep an eye on is that as your game evolves, your spatial structure will need to adapt to take
into account objects that move, objects that have been scaled/rotated, etc. Without proper gardening, it's easy to
generate bugs with object spawn/update/die lifecycles. In these cases, it may be wise to generate versions of spatial
grids, each one specialized to the objects that need it. For example, a static 2D binning grid is fine for static objects,
but dynamic ones may need a more aggressive quadtree hierarchy, or perhaps a k-dimensional tree.
Take care of your spatial grid, and it'll remain a strong data structure for your games.
Pixel Perfect Picking
For games that utilize picking for desktop applications, pixel-perfect response to a mouse click is crucial. Multiple
images can be overlaid against each other, and each one can have varied alpha footprints which in no way match their
conservative bounding box estimates. As such, to do a pixel-perfect pick of an object on the screen, you'll need to be
able to determine what pixel from what image was clicked on and what object instance that image belongs to.
In order to do this in HTML5, you need to introduce two separate data structures, a sprite prototype , which
represents a single loaded image sprite, and a sprite instance , which represents an instance of the prototype on the
canvas—that is, you assume that a single image is used multiple times on a canvas.
1.
The process for pixel-perfect picking is really straightforward. You need to load an image,
somehow get access to its pixel data, and keep that around in memory for access later.
2.
As objects are created and drawn to screen, you need a reference back to what image
it's using.
3.
When the user clicks, you need to find what objects intersect with that click, and then
per-object, check if the click has hit a transparent or opaque section of the image
representing that object.
 
Search WWH ::




Custom Search