It is common in physics based games to need to be able to drag bodies around. However, setting the position of a body instantaneously based on the current touch position can introduce excessive forces to the physics simulation, and break it. So we need another way to solve this problem…
Enter Box2D’s mouse joint. In our modifications to the ti.box2d module, we have added the mouse joint for use in Titanium games using Box2D. Creating a mouse joint is simple, as shown in the code below.
In the above code sample , world is the result of a call to ti.box2d’s createWorld function. All joints require 2 bodies, even though we generally think of the mouse joint as really only effecting a single body. When creating mouse joints, that second body (the first parameter in this function) is generally a static ground body. The second parameter in our createMouseJoint function is the body that we want to drag around.
We’ll come back to the other options in a moment. First, let’s actually drag the body around. In order to have the body dragged towards a point, we must call the setTarget function on the mouse joint with the x and y coordinates that we want to drag the body to. You’ll generally want to do this in an update loop or anytime the mouse (touch point) moves.
That’s all you need to start dragging a body around. Now lets circle back to those other options in the creation of the mouse joint. The maxForce property is the maximum amount of force that will be applied to the body in order to get it to its target point. collideConnected indicates whether the draggableBody should be allowed to collide with the groundBody.
The last two properties, dampingRatio and frequencyHz, are the parameters you will need to tweak the most to get the kind of dragging feel that you want. If you want very tight dragging, you will need a higher frequency and damping ratio. If you want some oscillation after the body reaches it’s target point, you will want a damping ratio less than 1.0. Check out the Box2D Manual to learn more about these options.