Public Group

# 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.

## 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 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.normalize();
movevec *= 3.52
planetpos += movevec

##### 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 somewherefloat G = 6.6e-11; // or whatever this constant should bevoid 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;}

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 13
• 12
• 15
• 11
• 12
• ### Forum Statistics

• Total Topics
634152
• Total Posts
3015842
×