I would like to model a rotating "turret" on top of a tank-like object in 2D from the side view like pictured here:

tank with turret http://uofitorn.net/static/images/tankwithbox2dturret.png

Notice the faint outline of a gun protruding to the upper left courtesy of libgdx's debug renderer (the actual gun sprite is not being rendered).

How do I best implement this using Box2d? Should I use two bodies? If so, how? Or one body with two fixtures?

I tried using two bodies connected by a Revolute Joint, but the turret "gun" does not maintain a constant angle but instead rotates down until it is vertical and then just hangs there.

Or should I not model the turret aspect of the tank in box2d at all?


1 Answer 1


The approach using two bodies connected with a revolute joint is the best approach. It just sounds like you have already tried this but encountered a bug.

The simplest way to implement the rotating-towards-the-cursor part is to find the angle of the vector connecting the pivot point and the cursor, and call Body::setTransform on the turret every cycle. Use the following pseudo code as a starting point:

// pivotOffset is the displacement vector pointing from the turret body origin to the pivot point
// get the world co-ordinates of the pivot point
vector turretPivot = turretBody.getWorldPoint(pivotOffset);

// get the world co-ordinates of the cursor position
vector cursorPos = libgdxgetCursorPositionFunction();

// get the displacement vector between the cursor and the turret pivot
vector displacement = cursorPos - turretPivot;

// set the angle of the turret body to the angle of the displacement vector

Alternatively, look at my Simple Solution in this related answer to see how this would work with a prismatic joint.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .