Game Development Reference
In-Depth Information
Now you know that you can drag the mouse around the stage, and you
expect the body to follow the mouse pointer. Box2D will handle it for you,
however you need to specify the force of the joint. The more powerful the
force, the more immediate the body response will be when you move the
mouse. Just think about elastic holding the body to your mouse pointer.
The more the strength of the elastic, the more precise the movement.
The
maxForce
property allows us to decide the maximum force of the joint.
I am setting it quite strong, according to body mass:
jointDef.maxForce=1000*touchedBody.GetMass();
Now everything has been decided, and we are ready to create the joint based
upon the definition we just ended. So let's add the joint to the world with the
CreateJoint
method:
mouseJoint=world.CreateJoint(jointDef) as b2MouseJoint;
13. At the moment we are done with the joint. Anyway, people will expect the
body to move as long as they move the mouse, keeping the button pressed,
and release the object once they release the button. So at first we need to
add two listeners, to detect when the mouse is moved and when the mouse
is released:
stage.addEventListener(MouseEvent.MOUSE_MOVE,moveJoint);
stage.addEventListener(MouseEvent.MOUSE_UP,killJoint);
14. And now, the callback function
moveJoint
will be called each time
the mouse is moved, and it just updates the target of the joint. Do you
remember? You had previously set the target with the
target
property
of
b2MouseJointDef
, and now you can update the target acting directly
on
b2MouseJoint
itself with the
SetTarget
method. Where will the new
target be placed? On the new mouse position:
private function moveJoint(e:MouseEvent):void {
mouseJoint.SetTarget(mouseToWorld());
}
15. The
killJoint
function is called when the mouse button is released, so we
are going to remove the joint with the
DestroyJoint
method in the same
way you destroyed bodies with
DestroyBody
. Moreover, the joint variable
is set to
null
, and obviously the listeners are removed.
private function killJoint(e:MouseEvent):void {
world.DestroyJoint(mouseJoint);
mouseJoint=null;
stage.removeEventListener(MouseEvent.MOUSE_MOVE,
moveJoint);