Newtons first law of motion, simply put:
Every object in motion will stay in motion until acted upon by an
outside force.
If you want to change the motion of an object, you need to add an additional force. In this case, a stopping force. This force is in the opposite direction of your velocity, with the sole purpose of arresting that velocity.
So, you have the following criteria.
- The force can't be strong enough to reverse the velocity.
- The force is only applied when the object is in motion (or when you want to stop).
There are a few "named" forces that fit here.
- Friction. The resisting force from two solid objects moving against each other.
- Drag. Essentially friction, but with respect to an object moving through a fluid/gas.
Box2D has support for friction built into its simulation. When defining a fixture, you simply set the friction value:
fixtureDef.friction = 0.3f;
See the Box2D manual for more information (unfortunately, their manual is not really linkable to specific sections, so just search for "Friction is used to make objects slide along each other realistically").
Some things you'll want to think about when implementing a stopping force.
- Friction will be the easiest to "turn on" and start using, however, you'll need to increase your movement forces to overcome friction.
- Implementing your own stopping force will allow you better control, but will mean you'll need to add more of your own code.
Basically, the way you're doing things now is fine, and the results are expected. You just need to add some additional functionality to get the results you want.