Revolute joints are added between two bodies so that one body can spin around the other. In this example, we will add wheels to the basket.
Import the wheel PNG files from the resources folder into the project. Create two new global sprites called spriteWheelL
and spriteWheelR
in the MainScene.h
file.
We will first add a new function called addWheels
in the MainScene.m
file:
-(void) addWheels{ //left wheel wheelSpriteL = [CCSprite spriteWithImageNamed:@"wheel.png"]; float radius = wheelSpriteL.contentSizeInPoints.width * 0.5f; CCPhysicsBody *body1 = [CCPhysicsBody bodyWithCircleOfRadius:radius andCenter:wheelSpriteL.anchorPointInPoints]; body1.friction = 1.2; body1.type = CCPhysicsBodyTypeDynamic; wheelSpriteL.physicsBody = body1; [basketSprite addChild:wheelSpriteL]; //right wheel wheelSpriteR = [CCSprite spriteWithImageNamed:@"wheel.png"]; CCPhysicsBody *body2 = [CCPhysicsBody bodyWithCircleOfRadius:radius andCenter:wheelSpriteR.anchorPointInPoints]; body2.friction = 1.2; body2.type = CCPhysicsBodyTypeDynamic; wheelSpriteR.physicsBody = body2; wheelSpriteR.physicsBody = body2; [basketSprite addChild:wheelSpriteR]; wheelSpriteR.position = ccp(basketSprite.contentSize.width, 0); //physics Pivot Joint CCPhysicsJoint * pin1 = [CCPhysicsJoint connectedPivotJointWithBodyA:wheelSpriteL.physicsBody bodyB:basketSprite.physicsBody anchorA:wheelSpriteL.anchorPointInPoints]; CCPhysicsJoint * pin2 = [CCPhysicsJoint connectedPivotJointWithBodyA:wheelSpriteR.physicsBody bodyB:basketSprite.physicsBody anchorA:wheelSpriteR.anchorPointInPoints]; pin1.collideBodies = pin2.collideBodies = false; }
We created two new sprites, one for the left wheel and the other for the right.
Notice that here the wheels aren't added to the PhysicsWorld
node but the basketSprite
itself.
The body type is kept as dynamic, and the friction is set to 1.0
so that the wheels will rotate and not just glide over the surface.
The left wheel is set at the default location to the lower-left of the basket. The right wheel, however, is placed at x
distance equal to the width of the basket with the y
value kept at 0
.
Once the wheels are added, two physics joints of type CCPhysicsJoints
are created, called pin1
and pin2
. For the parameters, the respective wheelSprite
physics body is first given, and then the basket's physics body is provided as the other body. For the anchor point, the current wheel's anchor point is provided.
This is done for both the wheels.
Then, for both the revolute joints, the collideBodies
properties is set to false so that the wheel and basket bodies don't collide with each other.
Also, we will set the friction of the edgeLoop
physicsBody
property to 1.0f
through the following code:
loopNode.physicsBody.friction = 1.0;
18.191.60.249