Search code examples
objective-ccocos2d-iphonebox2dgame-physics

Box2d - mouse joint set to a specific point on an object


I have a Box2d iphone app (using cocos2d) that has a mouse joint in it, and whenever you use the mouse joint, it applies the force to the object at whatever point you clicked. I was wondering if there is a way to always have the force be applied to a certain point on the object, for example the center of it. The reason is that when my shape is a box, for instance, when I pick it up using the mouse joint, it spins so that wherever I clicked ends up toward the top. I would like to always pick up the object from, say the center of the object. I've tried amping up the inertial dampening, but wasn't quite getting the effect I wanted. Here is my current code:

b2Vec2 locationWorld = b2Vec2(newtouch.x/PTM_RATIO, newtouch.y/PTM_RATIO);
b2MouseJointDef md;
md.bodyA = physicsLayer.groundBody;
md.bodyB = touchedObject.body;
md.target = locationWorld;
md.maxForce = 2000;

b2World* w = [physicsLayer getWorld];
mouseJoint = (b2MouseJoint*)w->CreateJoint(&md);

touchedObject is the object I'm moving and it stores it's body as a property. This code works fine as is, it just has the nasty spinning.


Solution

  • You could change the target point to be the center of mass of the box:

    md.target = touchedObject.body->GetWorldCenter();
    

    This will make the joint pull the center of the box to where your finger is, instead of the point you touched. It will not stop it from spinning if it's already spinning though, so you might still want to use some angular damping on the body to make it feel a bit more like the user is actually touching it, rather than holding a pin stuck through the center of it :)