Game Development Reference
In-Depth Information
fishes.push(fish);
// then add touch and mouseover events to the fish.
fish.domElement.addEventListener("mouseover", fishMouseOver, true);
fish.domElement.addEventListener("touchstart", fishTouched, true);
container.appendChild(fish.domElement);
}
Setting the fish properties
This is where we set each fish's position to be in the middle bottom of the screen, plus a random x and z
offset between -250 and 250. We also give it a slightly random velocity and give it a gravity of -0.05, which
is the negative gravity value I mentioned earlier that makes the game a little more fun—the longer it takes
to hit the fish, the faster they move up.
fish.posX = HALF_WIDTH + randomRange(-250,250);
fish.posY = SCREEN_HEIGHT+100;
fish.posZ = randomRange(-250,250);
// give it a random x and y velocity
fish.velX = randomRange(-1,1);
fish.velY = randomRange(-1,-2);
fish.velZ = randomRange(-1,1);
fish.size = 1;
fish.gravity = -0.05;
Recycling the fish
We have to get rid of a fish when it explodes or goes off the screen. We could just take it out of the array
and forget about it, but this is bad for memory management. Even if a fish is cleared out of memory with
the garbage collector, it still takes CPU to constantly create new DOM elements and JavaScript objects.
function removeFish(fish) {
fish.enabled = false;
fish.domElement.style.visibility = "hidden";
spareFishes.push(fish);
}
So we've made a simple pooling system, when we've finished with a fish, we disable it (by setting its
enabled property to false) and add it into the spareFishes array. We leave its DOM element in our
document, but we set its visibility to “hidden”.
In the makeFish function, we check if there are any fish objects in this spareFishes array to reuse before
we make a new one.
 
Search WWH ::




Custom Search