Search code examples
vectorchipmunk

Rotate a body around its center by applying an orthogonal force to it in Chipmunk


I'm trying to rotate a body around its own center by applying an orthogonal (to the body direction) force and generating the torque needed. However, this also moves the body (naturally) and I need it only to rotate. Here is my code. Please note that I don't want to set the angle/direction manually, but trying to achieve it by using this rotation force.

cpFloat dot = cpvdot(turningN, cpvnormalize_safe(cpBodyGetRot(body)));
cpFloat cross = cpvcross(turningN, cpvnormalize_safe(cpBodyGetRot(body)));


cpVect rotN;
if (cross<=0) {
    rotN = cpvperp(cpvnormalize_safe(cpBodyGetRot(body)));
}else{
    rotN = cpvrperp(cpvnormalize_safe(cpBodyGetRot(body)));
}

cpVect rotF = cpvmult(rotN, 300*(1-dot));
cpBodyApplyForce(body, rotF, cpv(75,14));

turningN is the vector that dictates the direction the body should have. I make the dot product so that I apply less and less rotation as the body's direction goes towards the desired direction.

EDIT

So, as @DGH points out, we need to add a force of same direction and magnitude but opposing to our spinning force and towards the object's center. So, I only needed to add this line of code to make it work:

cpBodyApplyForce(body, cpvneg(rotF), cpvzero);


Solution

  • I don't know chipmunk, but I know a little physics - apply a second force to the center of the object in the opposite direction, and scale its magnitude appropriately to counter-act the undesired motion.

    It's like having a wheel that's attached to a stationary axle - when you apply a force to the edge of the wheel, it spins without moving forward, because the axle applies a reactionary force in the opposite direction.