You will now learn how to launch an object from the catapult. This will be accomplished by combining techniques into one smooth action, which you have already learned. Following are the steps:
Brick
. Set bricks size to be (25
, 25
) and its anchor point to be (0.5
, 0.5
). Enable physics and set its density to a high value such as 50.0, and its friction to be 1.0, and its elasticity to 0.@property (nonatomic, strong) CCNode *brick; @property (nonatomic, strong) CCPhysicsJoint *brickJoint;
These will be used to keep track of your brick when it is being used.
touchBegan
method in the following code:- (void)touchBegan:(UITouch *)touch withEvent:(UIEvent *)event { CGPoint touchLocation = [touch locationInNode:self]; //Is the touch location in the catapult arm? if (CGRectContainsPoint(self.catapultArm.boundingBox, touchLocation)) { //Move the touch node to the position of the touch. self.touchNode.position = touchLocation; //Attach a spring between the touch node and the catapult arm self.touchJoint = [CCPhysicsJoint connectedSpringJointWithBodyA:self.touchNode.physicsBody bodyB:self.catapultArm.physicsBody anchorA:ccp(0, 0) anchorB:ccp(15, 15) restLength:0.0f stiffness:3000.0f damping:150.0f]; //Setup the brick CCNode *brick = [CCBReader load:@"Brick"]; CGPoint brickPosition = [self.catapultArm convertToWorldSpace:ccp(35, 35)]; brick.position = brickPosition; [self.physicsNode addChild:brick]; self.brick.physicsBody.collisionMask = @[]; self.brick.physicsBody.allowsRotation = NO; self.brick = brick; self.brickJoint = [CCPhysicsJoint connectedPivotJointWithBodyA:brick.physicsBody bodyB:self.catapultArm.physicsBody anchorA:ccp(15, 15)]; } }
This adds a new brick to the scene and sets up its position. You will notice that rotation and collision have been disabled. This is to avoid weird behavior when the brick is in the catapult. Once it is released, these will be enabled again.
- (void)fireCatapult { if (self.touchJoint) { [self.touchJoint invalidate]; self.touchJoint = nil; [self.brickJoint invalidate]; self.brickJoint = nil; self.brick.physicsBody.collisionMask = nil; self.brick.physicsBody.allowsRotation = YES; } }
This should look very familiar by now. You invalidate the joint, and also the renewable collisions and rotation for the brick.
18.224.71.72