Moving bodies with mouse

Hey everyone,

I'm making a mouse controlled game where you affect the physics-based gameworld using a box that is directly controlled with the mouse. The box itself doesn't have any collision with the other objects, but I'm using it as a "magnet", so that you can grab other objects, and collide them with each other. The box itself should be a pointer that always follows the mouse perfectly.

Currently, I just set the box to the mouse position and velocity using SetOriginPosition and SetLinearVelocity. When the mouse is clicked, it checks to see whether there are any bodies behind it, and if so, then it creates a prismatic joint between them that is limited to nearly zero travel. This means that you can pick up objects with your "magnet" (mouse pointer).

So far so good, and it seems to work okay. The problem occurs when colliding the object you have picked up with the rest of the world. I have added a test using GetReactionForce so that the joint will break and you will drop the object if you whack it against a wall. However, if you just "scrape it off" slowly against a wall (static box), then the force never seems to get high enough to cause the joint to break, despite the fact that the objects start going crazy. I'm guessing this is because I'm setting the position directly, but the joint is trying to resolve the positions so that the distance is constrained to zero, and none of the objects are intersecting.

Is there some other property I could give the joint? I'd really like to give the position setting of the mouse priority over the strength of the joint.

Any help would be much appreciated!
For this I would use an extension of the mouse joint. You wouldn't need a physical mouse box, just use b2World::Query to find any dynamic bodies to attach. If you want the mouse joint to prevent rotation, you can add the rotation constraint that is used by the prismatic joint. I would give the translation and rotation constraints of the mouse joint some maximum force and torque and clamp it.

I haven't tested the GetReaction force routines, so if you use them, make sure the values make sense.
Thanks for your reply, I think I'll give the mouse joint a closer look 🙂

However, I just found that I got a similar problem, just running the "pyramid" test bed demo.

If you pan down, then use the mouse pointer to drag a box into the floor, it can continually penetrate the ground box if you drag it far enough. Surely no amount of force should allow it to penetrate like this? Is there a way round it?
You can modify b2_linearSlop to reduce the amount of overlap. However, Box2D requires a small amount of overlap to make stacking stable. Usually this overlap can be made less than a pixel.

Original thread: https://box2d.org/forum/viewtopic.php?t=97