Advertisement Jump to content
Sign in to follow this  

Help with 3d movement

This topic is 4662 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I'm sure that this is asked regularly but I can't find it. I have two objects in 3d space and want one to exert a gravitational pull on the other. I've worked out the force with which it is pulling the other one but want to know how i apply that so object b is pulled towards object a no matter where it is. ie a sun at x=0 y=0 z=0 and a planet at x=150000 y=100 z=100 moving towards the sun at 3.52 units per round. Thanks Philip

Share this post

Link to post
Share on other sites
So we could just have three vectors (let's pretend we have a vector class; if we don't, all the math is easy to break down to simple real numbers), the position of the sun "sunpos", position of planet "planetpos". You can move by another, "movevec".

So figure out the vector pointing from the planet to the sun, normalize it (make it one unit long; divide each term by the magnitude of the vector), and multiply that by far how you want to move...

So every frame you'd do something like this:
movevec = sunpos - planetpos;
movevec *= 3.52
planetpos += movevec

Share this post

Link to post
Share on other sites
Spoony only provides half the answer – his code will move the planet inwards at 3.52 units per frame, but provides no acceleration. Again assuming a vector-math environment, the complete solution for two-body gravitation is as follows (pseudocode):
struct Particle {
Vector location, velocity;
int mass;

Particle planet, sun; // set up appropriately somewhere
float G = 6.6e-11; // or whatever this constant should be

void DoGravitation(Particle p1, Particle p2){
Vector ds = p1.location - p2.location;
float force = G * p1.mass * p2.mass / ds.MagSquared;
// acceleration is in the direction of the other object,
// i.e. along the difference vector
p1.velocity -= (force * ds) / p1.mass;
p2.velocity += (force * ds) / p2.mass;

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using, you agree to our community Guidelines, Terms of Use, and Privacy Policy. is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!