Force and Torque to keep const vel/angvel on damped spaces

Discuss new features and future development.
Post Reply
Baxnie
Posts: 9
Joined: Fri May 10, 2013 7:54 pm
Contact:

Force and Torque to keep const vel/angvel on damped spaces

Post by Baxnie »

Hello

Recently I've started using a damping smaller than 1 on cpSpace.
Setting a constant velocity with cpBodySetVel was not very usefull after that.
To keep a constant velocity/angularVelocity on bodies, they needed a force/torque to be applied.
As calculating that is not really simple, these two misc functions were created to help, such as cpMomentForCircle.

They're based on cpBodyUpdateVelocity, isolating body->f and body->t.

Code: Select all

cpVect
cpForceForConstantVelocity(cpBody *body, cpVect velocity)
{
    cpAssertHard(!cpBodyIsStatic(body), "Body must not be static.");

    cpFloat mass = cpBodyGetMass(body);
    cpAssertHard(mass != INFINITY, "Mass must not be infinity.");

    cpSpace *space = cpBodyGetSpace(body);
    cpFloat dt = cpSpaceGetCurrentTimeStep(space);
    cpFloat dt_inv = 1. / dt;
    cpFloat damping = cpSpaceGetDamping(space);
    cpVect gravity = cpSpaceGetGravity(space);

    // f = ((v - g*dt - v*d^dt) * m) / dt
    return cpvmult(cpvmult((cpvsub(cpvsub(velocity, cpvmult(gravity, dt)), cpvmult(velocity, cpfpow(damping, dt)))), mass), dt_inv);
}

cpFloat
cpTorqueForConstantAngularVelocity(cpBody *body, cpFloat angularVelocity)
{
    cpAssertHard(!cpBodyIsStatic(body), "Body must not be static.");

    cpFloat moment = cpBodyGetMoment(body);
    cpAssertHard(moment != INFINITY, "Moment must not be infinity.");

    cpSpace *space = cpBodyGetSpace(body);
    cpFloat dt = cpSpaceGetCurrentTimeStep(space);
    cpFloat damping = cpSpaceGetDamping(space);

    // t = (m * w * (1 - d^dt)) / dt
    return (moment * angularVelocity * (1 - cpfpow(damping, dt))) / dt;
}
(posting it here cause my last pull request on github was never accepted, rejected or commented)

This is a fine solution for now, however it would be less expansive to replace update velocity function of objects that I need to keep constant velocity.
It would be nice if Chipmunk have a few built-in cpBodyUpdateVelocity functions as:
ignore gravity, ignore velocity damping, ignore angular velocity damping

Thanks
Post Reply

Who is online

Users browsing this forum: No registered users and 4 guests