Game Development Reference
In-Depth Information
While you're optimizing this code, why not get rid of the unnecessary memory alloca-
tions and releases caused by the Bullet class? Allocating and releasing memory is an
expensive operation you should aim to minimize during game play. A common solu-
tion is to instantiate a fixed number of objects when the game starts and then simply
enable or disable/hide the objects as needed. This is called object pooling .
Because you can safely define an upper limit for the number of bullets that can be on
the screen at the same time, bullets are an excellent candidate for pooling to avoid al-
locating and releasing bullets during game play. Because the bullets share the same tex-
ture, the additional memory used by having a greater number of bullets that resides in
memory at all times is negligible. Listing 6-8 shows the changes to GameScene 's
init method implemented in the Sprites01 project.
Listing 6-8. Creating a Reasonable Number of Bullet Sprites Up Front Avoids Unne-
cessary Memory Allocations During Game Play
CCSpriteBatchNode* batch = [CCSpriteBatchNode batchNodeWithFile:@"bullet.png"];
[self addChild:batch z:0 tag:GameSceneNodeTagBulletSpriteBatch];
// Create a number of bullets up front and reuse them whenever necessary.
for (int i = 0; i < 400; i++)
Bullet* bullet = [Bullet bullet];
bullet.visible = NO;
[batch addChild:bullet];
All the bullets are made invisible because you don't use them just yet. The GameS-
cene class gets a new method in Listing 6-9 that allows it to shoot bullets from the
ship by reactivating inactive bullets in sequence. This process is often called object
pooling . Shooting is now rerouted through the GameScene because it contains the
CCSpriteBatchNode used for the bullets. Once an inactive bullet has been selec-
ted, it's instructed to shoot itself.
Listing 6-9. Shooting Is Now Rerouted
-(void) shootBulletFromShip:(Ship*)ship
Search Nedrilad ::

Custom Search