(No. 00002) prototype of iOS game genie war (7)
In the previous post, we continue to complete the shooting function.
Add the initBullets method in MainScene. m:
-(void)initBullets{ CCSprite *bullet; for (int i = 0; i < MAX_BULLET_COUNT; i++) { bullet = (CCSprite*)[CCBReader load:@Sprites/Bullet]; bullet.positionType = CCPositionTypeNormalized; bullet.visible = NO; [_bullets addObject:bullet]; [_physics addChild:bullet]; }}
This method is used to cache bullets in advance. The value of MAX_BULLET_COUNT is 10, which indicates that we have created 10 bullets in advance. These 10 bullets can be reused, resulting in an infinite illusion of bullets. let's take a look at how to create a bullet:
First load Bullet. the ccb file is included in the bullet variable. Do not ask why the Code does not exist. ccb suffix. As mentioned in the popularity of SpriteBuilder, you can search for it. then modify the bullet position type. The bullet is invisible because it has not been fired. add the bullets to the bullet array and physical objects respectively.
It should be noted that the bullet cannot be directly added to the MainScene scenario. Because the bullet is a physical object, it can only be added to the physical world.
Modify the didLoadFromCCB method and add the following code at the end:
[self initBullets];
The bullet Initialization is complete, but the bullet still cannot be used at this time. A bullet needs to be loaded. After the bullet is loaded, it can be actually launched. Then, a loadBullet method is added:
-(CCSprite *) loadBullet {static NSInteger last = 0; for (CCSprite * bullet in _ bullets) {if (! Bullet. visible) {bullet. visible = YES; return bullet ;}// if all bullets are visible, take the CCSprite * bullet = _ bullets [last] with the longest visibility time; last = (last + 1) % MAX_BULLET_COUNT; return bullet ;}
As mentioned above, the bullets in the cartridge are invisible by default. Once the bullet is fired, it becomes visible. find the first invisible bullet here, load it, and make it visible, ready to be shot. what if all bullets are visible at this time? This means that all the bullets in the cartridge have been shot. we must recycle the bullets that have been shot. We should select the first one. Note that the last variable in the method is static.