Game Development Reference
In-Depth Information
CCArray* bullets = [self.bulletSpriteBatch children];
CCNode* node = [bullets objectAtIndex:nextInactiveBullet];
NSAssert([node isKindOfClass:[Bullet class]], @"not a bullet!");
Bullet* bullet = (Bullet*)node;
[bullet shootBulletFromShip:ship];
nextInactiveBullet++;
if (nextInactiveBullet >= bullets.count)
{
nextInactiveBullet = 0;
}
}
By keeping the reference counter nextInactiveBulle t , each shot uses the sprite-
batched bullet from that index. Once all bullets have been shot once, the index is reset.
This works fine as long as the number of bullets in the pool is always greater than the
maximum number of bullets on the screen.
The Bullet class's shoot method in Listing 6-10 only performs the necessary steps
to reinitialize a bullet, including rescheduling its update selector by first unscheduling
the update selector in case it's already running. Most importantly, the Bullet is set to
be visible again. Its position and velocity are also reset. The Bullet class's shoot
method simply resets the relevant variables such as position and velocity and then sets
the bullet to be visible. Once the bullet has reached the end of its lifetime, it's simply
set to not be visible again.
Listing 6-10. The Bullet Class's Shoot Method Reinitializing a Bullet
-(void) shootBulletFromShip:(Ship*)ship
{
float spread = (CCRANDOM_0_1() - 0.5f) * 0.5f;
velocity = CGPointMake(1, spread);
outsideScreen = [CCDirector sharedDirector].winSize.width;
self.position = CGPointMake(ship.position.x + ship.contentSize.width * 0.5f, ←
ship.position.y;
 
 
Search Nedrilad ::




Custom Search