(No. 00004) Implementing brick-hitting games for iOS (14th): 3. Implementing ball props
We have already introduced how to change the items of the bounce stick. Below we can make some articles on the ball to realize more items.
We call it a three-ball prop: When a bounce stick hits this item, the ball turns into three. Next, keep these balls as close as possible, in this way, you can get more scores than one ball.
Open Xcode and add a new branch to the spawnStar method condition in Star. m:
case brkColorPurple:
star = [Star starWithType: starTypeThreeBalls];
break;
Because you need to know the state of the ball in the current scene in the method of Star.m, first add 2 new methods to the GameScene.h interface:
-(void) addBall: (CCSprite *) ball;
-(NSInteger) currentBallsCount;
Back in GameScene.m, the extension code adds a new instance variable to represent all the current balls:
NSMutableArray * _balls;
Then we implement the two new methods added above:
// Add a ball in GameScene, the position of the ball must have been set correctly
-(void) addBall: (CCSprite *) ball {
@synchronized (self) {
[_physicsWorld addChild: ball];
[_balls addObject: ball];
}
}
-(NSInteger) currentBallsCount {
@synchronized (self) {
return _balls.count;
}
}
Note that synchronization is set in the method, because it may be modified when reading, and if synchronization is not added, the app may crash!
Back in Star.m, we add the key prop function method doThreeBalls:
+ (void) doThreeBalls: (CGPoint) ballLocation {
GameScene * gameScene = [GameScene sharedGameScene];
if ([gameScene currentBallsCount]! = 1) {
return;
}
CCSprite * ball2 = (CCSprite *) [CCBReader load: @ Elements / Ball];
ball2.position = ballLocation;
[gameScene addBall: ball2];
CCSprite * ball3 = (CCSprite *) [CCBReader load: @ Elements / Ball];
ball3.position = ballLocation;
[gameScene addBall: ball3];
}
The code first checks how many small balls are in the current scene, and if there is more than one, it returns directly, which means that the prop can only play a role when there is only one small ball.
Then create another 2 small balls and add them to the scene through the addBall method defined previously.
Finally, add a new selection branch to the collision processing of GameScene.m:
case starTypeThreeBalls:
@synchronized (self) {
if ([self currentBallsCount]> = 1) {
[self scheduleBlock: ^ (CCTimer * timer) {
[Star doThreeBalls: ((CCSprite *) _ balls [0]). Position];
} delay: 0];
}
}
break;
Now compile and connect the app and run the effect as follows: