Rotating a body around its own ax using only forces

Official forum for the Chipmunk2D Physics Library.
Post Reply
mindnoise
Posts: 1
Joined: Fri Aug 17, 2012 5:58 pm
Contact:

Rotating a body around its own ax using only forces

Post by mindnoise »

I'm trying to rotate a body around its own ax by applying two forces, one orthogonal to the body's direction at an offset of 75 units (half the shape size) and an opposing one towards the center of the object and parallel with the first force. It works fine, up to the point when the object points down, when it stops, and I can move it from that direction. I don't use any gravity or other forces, so I wonder what my be the problem. Here is my code: (targetLocation is the point where I would like my body to point to)

Code: Select all


    cpVect turningN = cpvnormalize_safe(cpvsub(targetLocation, cpBodyGetPos(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);
    cpBodyApplyForce(body, rotF, cpv(75,0));
    cpBodyApplyForce(body, cpvneg(rotF), cpvzero);

User avatar
slembcke
Site Admin
Posts: 4166
Joined: Tue Aug 14, 2007 7:13 pm
Contact:

Re: Rotating a body around its own ax using only forces

Post by slembcke »

What is rotN for exactly? Not sure I understand why it has to change

I'd approach that a bit differently I think. If you do cpvunrotate(cpBodyGetRot(body), turningN), it will give you the direction of the body relative to the direction you want it to go. Then you can just do cpvtoangle() to get the relative angle in the range (-pi, pi). If you want it to act like a spring force, just multiply that relative angle by a some hand tweaked constant (which should be negative unless I got that backwards).

A spring force will make it oscillate though. If you want to add damping to it as well, use a damped spring joint and override the spring force function on it to calculate the force like above. If you want to make it act smooth and servo-like, you could use a gear joint with a ratio of 1.0, and a finite maxForce.

Also, cpBodyGetRot(body) should *always* be a unit length vector unless the angle got set to NaN/infinity somehow. No need to renormalize it.
Can't sleep... Chipmunks will eat me...
Check out our latest projects! -> http://howlingmoonsoftware.com/wordpress/
Post Reply

Who is online

Users browsing this forum: No registered users and 9 guests