Previous Entries in Series
My next short term goal was to get some of spheres to show and animate. And that was going to entail using HTML5’s new <canvas> tag. I saw two ways of going about animating the spheres. The first way would be to manually draw the spheres on a single canvas and animate them by clearing the canvas and redrawing at every game cycle. The second way would be to create a separate canvas for each sphere and use CSS3 to animate them. The latter method would allow the GPU to help accelerate the graphics processing and seems to be the best choice for animations of this type in HTML5 (see this blog entry from Jeff Prosise).
The solution in HTML5 is to use the new requestAnimationFrame method. However, this API is still in the development stages and is not supported by all modern browsers (once again Internet Explorer 9.0 falls behind, but the API is supported in IE 10). Paul Irish has a very good explanation and a workable fallback routine that I will be using for Cascade Html5.
The animation heart of Cascade looks essentially like most traditional game loops, like this:
The startLevel() function is called by the main application and dynamically creates the game resources (i.e. the spheres) for a particular game level before starting the game timer.
The gameLoop() function is the routine that animates each sphere in relation to the others. This method is responsible for two things during each animation cycle: 1) move each sphere, and 2) check for collisions with an explosion. I’m using a rather basic loop to iterate through all the spheres and avoiding double-checking collisions. Here’s the code:
The USE_COLLISIONS variable is a simple boolean that I can use to globally turn off the rudimentary physics in the game. The sphere class encapsulates the logic for all movement and collision detection. The gameLoop() routine simply tells to each sphere to move itself and then determine if they collide with each other. Remember the gameLoop() routine should be running approximately 60 times every second.