- Mouse Joint
-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event { CGPoint touchLocation = [touch locationInView:[touch view]]; touchLocation = [[CCDirector sharedDirector]
convertToGL:touchLocation]; touchLocation = [self convertToNodeSpace:touchLocation]; b2Vec2 locationWorld =
b2Vec2(touchLocation.x/PTM_RATIO, touchLocation.y/PTM_RATIO);
b2AABB aabb; b2Vec2 delta = b2Vec2(1.0/PTM_RATIO, 1.0/PTM_RATIO); aabb.lowerBound = locationWorld - delta; aabb.upperBound = locationWorld + delta; SimpleQueryCallback callback(locationWorld); world->QueryAABB(&callback, aabb);
if (callback.fixtureFound) { b2Body *body = callback.fixtureFound->GetBody(); b2MouseJointDef mouseJointDef; mouseJointDef.bodyA = groundBody; mouseJointDef.bodyB = body; mouseJointDef.target = locationWorld; mouseJointDef.maxForce = 50 * body->GetMass(); mouseJointDef.collideConnected = true;
mouseJoint = (b2MouseJoint *)
world->CreateJoint(&mouseJointDef);
body->SetAwake(true);
return YES; }return TRUE; }
-(void) ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event { CGPoint touchLocation = [touch locationInView:[touch view]]; touchLocation = [[CCDirector sharedDirector]
convertToGL:touchLocation]; touchLocation = [self convertToNodeSpace:touchLocation]; b2Vec2 locationWorld = b2Vec2(touchLocation.x/PTM_RATIO,
touchLocation.y/PTM_RATIO);
if (mouseJoint) { mouseJoint->SetTarget(locationWorld);} }
-(void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event { if (mouseJoint) {
world->DestroyJoint(mouseJoint);
mouseJoint = NULL; }}
2. Revolute Joint
wheelL = [Box2DSprite spriteWithSpriteFrameName:@"Wheel.png"];
wheelL.gameObjectType = kCartType;
wheelLBody = [self createWheelWithSprite:wheelL
offset:b2Vec2(-63.0/100.0, -48.0/100.0)];
b2RevoluteJointDef revJointDef;
revJointDef.Initialize(body, wheelLBody,
wheelLBody->GetWorldCenter());
revJointDef.enableMotor = true;
revJointDef.maxMotorTorque = 1000;
revJointDef.motorSpeed = 0;
///////////////////////
//restrict revolute joints
to a certain angle range with Box2D
revJointDef.lowerAngle
= CC_DEGREES_TO_RADIANS(-30);
revJointDef.upperAngle
= CC_DEGREES_TO_RADIANS(60);
revJointDef.enableLimit
= true;
wheelLJoint = (b2RevoluteJoint *) world->CreateJoint(&revJointDef);
3. Prismatic Joint
3. Prismatic Joint
A prismatic joint is a type of joint that restricts two bodies so they can move relative
to each other only along a specified axis.
b2PrismaticJointDef prisJointDef;
prisJointDef.Initialize(body, legsBody,
legsBody->GetWorldCenter(), axis);
prisJointDef.enableLimit = true;
prisJointDef.lowerTranslation = 0.0;
prisJointDef.upperTranslation = 43.0/100.0;
world->CreateJoint(&prisJointDef);