# Constant rotation of a revolute joint in box2d

I would like to have a line with one end attached to a location and have it rotate constantly (with the same speed) with a maximum of 45 to -45 degrees (i.e. I would like to have it swing like a rope back and forth 90 degrees).

Is this possible or should I use non box2d objects to do this (cheat box2d engine)?

That's certainly possible, but you might have do some tests to find the exact forces needed so that it works to your satisfaction.

Almost all joints can have a "motor" which you can enable and which applies a force to your joint. So in your case you have to set:

myJoint->EnableMotor(true);
myJoint->SetMaxMotorTorque(yourTorque);
myJoint->SetMotorSpeed(yourMotorSpeed);


You'll have to experiment with the torque.. I suggest you start with a pretty high value, so that the motor doesn't get hindered too much by other objects or objects attached to the joint. Also, if you want to limit the joint movement, you have to enable the joint limits. In the following example the joint would be limited to -90 to 90 degrees.

myJoint->EnableLimit(true);


The only thing left to do is to check if the joint reaches a limit and then switch direction. So in your update loop you would do something like:

float speed = myJoint->GetMotorSpeed();
float angle = myJoint->GetJointAngle();
if((speed < 0.0f  && angle <= myJoint->GetLowerLimit()) ||
(speed > 0.0f  && angle >= myJoint->GetUpperLimit())
){
// reverse motor speed whenever we overshoot limits
myJoint->SetMotorSpeed(speed * -1.0f);
}


That should make your joint swing around from -90 to 90 degrees.

If you want to have it rotate at a constant speed, there's no reason to use a physics engine. Simply draw the line rotating one way then the other.

However, if you're actually interested in a swinging motion, constant speed is not going to give a very realistic interpretation. Check out pendulum motion to see the math behind the motion of a swinging object. Even with a pendulum, you shouldn't need the physics library to simulate it. You don't mention you'll have anything interacting with it, so just use a simple harmonic motion formula for movement.