HTML and CSS Reference
In-Depth Information
Representing Objects
Now that you have your images loaded and in a form you can reference, you need to generate the actual objects that
will populate your canvas and be targets for picking. To this end, you create a new SpriteInstance class.
You'd expect the basic two parameters of this class, position and size , which you will use for picking later. You also
add a few other parameters: a unique ID value, alongside a ZIndex , which is useful for sorting during rendering, and
collision resolution. And of course, you need a reference to what ProtoSprite object you'll be using to render
(see Listing 5-3).
Listing 5-3. Definition of a SpriteInstance
function SpriteInstance(){; //the unique ID for this object
this.zIndex=50; //needed for rendering and picking resolution, range [0,numObjects]
this.spriteHandle=null; //what sprite we'll use to render
For your simple uses, you need to populate the world with pickable objects, and to do so, you simply flood
the given canvas with randomly placed objects. Note that you store the generated sprites in a global array for other
systems to access later on (see Listing 5-4).
Listing 5-4. Populating the scene with randomly located SpriteInstances
var spriteInstances = new Array(); //global list of active sprites
function generateInstances()
var numSprites = 4096; //magic number
for(var i = 0; i < numSprites; i++)
var sp = new SpriteInstance(); = i;
sp.zIndex = i; //just to keep my sanity...
sp.pos.x = Math.floor(Math.random() * (500)); //random point on canvas
sp.pos.y = Math.floor(Math.random() * (500));
//choose a random sprite to render this with
var idx = Math.floor(Math.random() * (protoSprites.length));
sp.spriteHandle = protoSprites[idx];
sp.size = sp.spriteHandle.size;
When you'd like to draw the sprites, you simply iterate over each instance, fetch its corresponding spriteHandle ,
and use that to draw to the canvas with the correct position data (see Listing 5-5).
Search WWH ::

Custom Search