(No. 00003) iOS games simple robot projection game forming notes (21)
Return to Xcode and add the collision protocol to the MainScene. h Interface:
@interface MainScene : CCNode
//...@end
Then enable the collision proxy in the MainScene. m initialization method:
_physicWorld = (CCPhysicsNode*)[self getChildByName:@physicWorld recursively:YES]; NSAssert(_physicWorld, @physicWorld must not nil); _physicWorld.collisionDelegate = self;
Because we want to deal with the collision between bullets and sensors, we need to add the corresponding collision callback method:
-(BOOL)ccPhysicsCollisionBegin:(CCPhysicsCollisionPair *)pair bullet:(CCNode *)bullet sensor:(CCNode *)sensor{ CCPhysicsBody *phyBullet = bullet.physicsBody; phyBullet.collisionType = @null; [self scheduleBlock:^(CCTimer *timer){ bullet.visible = NO; bullet.position= ccp(0, 0); } delay:5]; _score++; _scoreLabel.string = [NSString stringWithFormat:@Score:%d,_score]; return NO;}
First, obtain the physical object of the bullet and change the collision type to @ "null". This is because the following situations may occur:
A bullet first enters the basket and comes into contact with the sensor. However, it may hit the wall of the basket and rebound upwards and leave the sensor. Then, it falls into the sensor, causing a bullet to enter the basket for scoring multiple times.
After setting the collision model as @ "null", the bullet that has already encountered the sensor will no longer collide with the sensor. Of course, this is only a solution.
Next, we will wait five seconds to set the bullet to invisible and remove it from the basket. This will not affect other injected bullets, but can be reused.
Last score, and update the score tag in the Hud layer.
Compile and run the game. The final effect is as follows:
The steps for creating the Hud layer are omitted. After the first few exercises, this should be skipped.
This game has come to an end now. The next game No. 00004 will develop a game similar to playing bricks with a ball. See you later ;)