Chipmunk 2D Setting Oribital Velocity Function
So I've used the Planet.c demo to set up a velocity function for my 2D iPhone game that's in the works that involved orbiting planets. However the following code sets up nice orbits but only does so around the origin of the screen i.e. the lower left corner of the screen:
// Point mass pos开发者_如何学Cition
cpVect p = body->p;
cpFloat sqdist = cpvlengthsq(p);
cpVect g = cpvmult(p, -gravityStrength / (sqdist * cpfsqrt(sqdist)));
cpBodyUpdateVelocity(body, g, damping, dt);
I've tried simply adding a displacement vector of the central star's position (in this case the center of the screen cpv(160, 240)) but that just sends it off in a strange orbit. I've always tried a variety of trying to get my body's position vector and radial vector in relation to the center as opposed to the origin but I can't get it to work quite right. I'm thinking something along the lines of:
// Sun position
cpVect disp = cpv(160, 240);
// Point mass position
cpVect p = body->p;
// Point mass relative to Sun
p = cpvsub(disp, p);
cpFloat sqdist = cpvlengthsq(p);
cpVect g = cpvmult(p, -gravityStrength / (sqdist * cpfsqrt(sqdist)));
cpBodyUpdateVelocity(body, g, damping, dt);
Any ideas? Thanks!
Got it! As I suspected was just a matter of getting the right vector subtractions namely the center minus the position vector. Well done!
精彩评论