Game Development Reference
In-Depth Information
var requestAnimationFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame || wi ndow.mozRequestAnimationFrame ||
window.msRequestAnimationFrame || function(f){window.setTimeout(f, 5); }
Micro optimizations
We can gain some additional performance by tweaking details in the code. Very often, this means trading
readability for a little more speed. This is usually a very bad idea, but it can help to make inner loops
significantly faster.
Micro optimizations are heavily dependent on the browser, so always time them to make sure they are
actually faster. A good tool to perform this is found at jsfiddle.net . The more advanced JavaScript
engines become, the less important these micro optimizations will become.
Chaining expressions
Looking up the value of a variable costs time. We can save some property lookups by chaining
expressions. Thus,
vy += gravity*td;
y += vy;
can be rewritten as
y += (vy += gravity*td);
Rounding
The bitwise complement operator is used to round numbers. As it is a bitwise operator, it will convert the
float value of the number into an integer and then flip all of its bits. By doing this twice, we can round a
number. So instead of:
drawImage(img, Math.floor(x), Math.floor(y));
you can simply write:
drawImage(img, ~~x, ~~y);
Optimized fireworks
By putting together all those optimizations, we can handle a lot of particles.
(function(){
// fall back to normal arrays if the browser does not support
// float 32 arrays
var MAX_PARTICLES = 100000,
NFIELDS = 5, // x, y, vx, vy, age,
// size of the array
 
Search WWH ::




Custom Search