Hydroque's method is definitely a valid option, but there is also another option using physics, which IMO is a good option since box2d is a physics engine, but either will work. The upside to this is that you aren't risking messing up the physics simulation by manually editing positions.
So you have this diagram here, a box rotating at a distance r
(center to center) from an object with velocity v
and has a constant speed.
Now imagine the orbiting box is attached to the center object by a string. In order for that box to keep rotating around the center, the string needs to apply a force to it.
However the acceleration here is centripetal acceleration because it is an object rotating at a constant radius and constant speed around an object.
Centripetal acceleration is
so we can plug that in to the original equation
In order to keep the box rotating around the center object, you need to apply a force which is equal to
on the center of the orbiting object towards the center position. However you also have to make sure it has an initial velocity, otherwise it would just fall in to the center object. That initial velocity is just v
and it needs to be tangent to the orbiting circle. For example, if the box starts on top, the velocity needs to be v
in the positive or negative x direction.
Now if you want to have the object always facing the center: think of the moon. The same side of the moon always faces the Earth. This is because it takes the moon the same time to orbit around the Earth as it does for the moon to complete one full rotation.
The time it takes (in seconds) for the object to complete one rotation around the center is called the period (which is noted as T
). The equation is:
Now we can find the angular velocity so that the object always faces the center. The angular velocity is measured in radians per second. The object needs to rotate one full rotation, in the time it takes to travel once around the orbit. So, since we need to travel 2 PI
radians in T
seconds, we can find the angular velocity by using the equation:
which conveniently ends up being
So to have the object always face the center, you need to set its angular velocity to be v
and have its initial rotation be facing the object.
I wrote out the code for this and it is working, so if you decide to take this approach and run in to trouble I can gladly help you out.