HTML and CSS Reference
In-Depth Information
Updating Only What's Important
It may be worth noting that not every item in the world needs to be alive and in memory. For instance,
a two-dimensional side-scrolling game doesn't need to simulate enemies at the end of the level; also, more important,
any particles that are offscreen shouldn't be rendered. If the player only moves forward, you may discard everything
behind the player past a certain point to save both memory and central processing unit (CPU) cycles. Just make sure
the player cannot walk backward and fall into the void!
Depending on your game, the cost of keeping objects rather than discarding them may be high. For example, not
discarding enemies may cause physics-, artificial intelligence- (AI-), and rendering-related functions to be called way
more than is necessary.
To get an idea of your game functions' execution times, you may use the Chrome DevTools CPU Profiler, which
will give you a good idea of where your game is spending most of its time. Note that this profiler is a sampling profiler,
meaning that it collects data periodically (at 1ms intervals), so you may want to collect samples over a relatively
large period of time (for example, a few seconds) to get an accurate picture. There is also a structural profiler in
Chrome, which you can find at chrome://tracing . I highly recommend that you check the great Chrome DevTools
documentation for more information on those tools as well as this Google Developers Live show about profiling in
Chrome: https://developers.google.com/live/shows/7327030-5001 .
Also, now that you are using a pool, you can simply return your objects to their respective pools for reuse later
on. For instance, if your game is like Sonic Jump ( www.sega.com/games/sonic-jump ), you may want to return both
platforms and enemies to their respective pools when they are below a certain point in order to retrieve them at a later
time to place above your hero.
Culling for Simulation
Discarding particles as soon as they are offscreen is the simplest task in the demo. Figure 3-4 shows a drop in CPU
usage when culling is turned on.
Figure 3-4. Discarding offscreen particles decreases CPU usage
In your loop, you call the following function and discard the particle if it returns false :
isInBounds = function( particle ){
var x = particle.pos.x,
y = particle.pos.y,
w = particle.size.y,
h = particle.size.x,
areaW = demo.settings.width,
areaH = demo.settings.height;
return !(x > areaW || x + w < 0 || y > areaH || y + h < 0);
}
 
Search WWH ::




Custom Search