(No. 00004) implementing the brick-hitting game for iOS (9): collision between the ball in the game and the rebound Rod
The previous blog post introduced the collision processing between small balls and bricks in physical objects. In this article, let's take a look at the collision between small balls and rebound rods ;)
The ball starts to collide with the rebound rod.
Similarly, we also need to adjust the torque of the ball in the collision, so we also need to separate the processing, first of all, the processing at the beginning of the collision:
-(BOOL) ccPhysicsCollisionBegin :( CCPhysicsCollisionPair *) pair ball :( CCNode *) ball stick :( CCNode *) stick {// restore score ratio when the ball hits the rebound rod _ scoreRatio = 1; return YES ;}
Previously we realized that the score ratio will be increased when the ball repeatedly hits the bricks consecutively, so here we need to reset the score ratio when the ball hits the rebound rod. this is all of his work. in fact, you can put it in the end collision, and then completely remove the start collision processing.
Ball and rebound Rod End Collision
Next we will handle the collision:
-(BOOL) ccPhysicsCollisionPreSolve :( CCPhysicsCollisionPair *) pair ball :( CCNode *) ball stick :( CCNode *) stick {CCPhysicsBody * phyBall = ball. physicsBody; CGPoint velocity = phyBall. velocity; NSInteger neg = arc4random_uniform (2); NSInteger rnd = arc4random_uniform (500); // if (neg = 0) {velocity. x + = rnd;} else velocity. x-= rnd; [phyBall applyImpulse: ccpMult (velocity, 1.3)]; return YES ;}
The method code is not long, but involves some operations on physical objects. It is necessary to elaborate:
First, obtain the physical object of the ball, then randomly generate a force of the ball, and then apply the force to the ball. That's all!
Rebound rod Movement
Now we want to implement the movement function of the bounce rod. In GameScene. m, add the mobile touch method:
-(void)touchBegan:(CCTouch *)touch withEvent:(CCTouchEvent *)event{ //CCLOG(@touch began from GameScene);}-(void)touchMoved:(CCTouch *)touch withEvent:(CCTouchEvent *)event{ CGPoint location = [[CCDirector sharedDirector] convertTouchToGL:touch]; @synchronized(self){ [self.stickInGameScene moveStickTo:location]; }}
Compile and run the app. The current game effect is as follows:
Now the game has a certain degree of playability. In the next article, we will go back to the level and let it continuously generate more bricks. See the next article ;)