HTML and CSS Reference
In-Depth Information
Firstly, the findClickedSprite function will loop through all the sprite instances in memory and do a bounding
box test against the picking point; you assume that array lookup is a performance limiting action in JavaScript, and
this bounding-box test allows an early out for items that don't potentially intersect with the pick position.
Once you find a sprite instance whose bounding box intersects with the picking point, you grab the sprite
prototype and translate the canvas-relative mouse position to a sprite-instance-relative position that you use to
test against.
that you're still utilizing the bounding-box picking style covered earlier. per-pixel picking is quite an intensive
inner-loop operation: the lookup and calculation of pixel data will easily cause performance problems. as such, using a
bounding-box specific test first allows you to create a list of “potential” selected sprites (omitting objects that don't
intersect with the target in any way) which you can then continue forward with to do pixel-perfect testing on.
Note
These values are passed to a function on the sprite prototype to determine if the target pixel is transparent or not.
If you're clicking an opaque pixel for this sprite, you set this as the selected sprite (see Listing 5-12).
Listing 5-12. Updating the findClickedSprite function to take into account pixel-based picking
function findClickedSprite(x,y)
{
var pickedSprite = null;
var tgtents = spriteInstances;
//loop through all sprites
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)
continue;
var ps = sp.spriteHandle;
//get local coords and find the alpha of the pixel
var lclx = x - sp.pos.x;
var lcly = y - sp.pos.y;
if(!ps.isPixelTransparent(lclx,lcly))
{
pickedSprite = sp;
}
}
}
Again, in this particular example, you're somewhat naive about z-index collisions and visible ordering to the user.
The fix for this is somewhat simplistic: if you've found a pick collision, you test the zIndex of the new sprite with the
zIndex of the existing picked sprite to see which one is closer to 0 (which represents closer to the camera), as shown in
Listing 5-13.
 
 
Search WWH ::




Custom Search