Benjamin Jameson
Benjamin Jameson

Reputation: 41

How to make Gravity for multiple planets in Unity3d

What i'm looking to do is something similar to our solar system, where you are gravitically drawn to one planet till you leave it's pull, and then once you're on another planet be drawn to that gravity.

I have found many entries online about how to create gravity for a single planet, but none i've found work for multiple sources.

Any help would be GREATLY appreciated.

Projects I've already looked at were mainly for single planet gravity.

unity 3.3, create local gravity on object

http://answers.unity3d.com/questions/13639/how-do-i-make-a-small-planet-with-gravitational-pu.html

http://answers.unity3d.com/questions/701618/how-could-i-simulate-planetary-gravity-that-has-an.html

Upvotes: 4

Views: 4681

Answers (1)

Dinal24
Dinal24

Reputation: 3192

This could be done easily by adding a normal force relative to the planet on the surrounding objects.

According to physics of Universal gravitational force you can calculate the gravitational force. Then calculated the normal force at the moment and add the force.

void FixedUpdate(){
    // Do the Force calculation (refer universal gravitation for more info)
    // Use numbers to adjust force, distance will be changing over time!
    forceSun = G x (massPlanet x massSun)/d^2;

    // Find the Normal direction
    Vector3 normalDirectionSun = (planet.position - sun.position).normalized;

    // calculate the force on the object from the planet
    Vector3 normalForceSun = normalDirection * forceSun;

    // Calculate for the other systems on your solar system similarly
    // Apply all these forces on current planet's rigidbody

    // Apply the force on the rigid body of the surrounding object/s
    rigidbody.AddForce(normalForceSun);

   // .... add forces of other objects. 
}

With various m1, m2 values you will be able to make the system more realistic. As an example make the object move/accelerate towards the planets with higher mass.

Upvotes: 3

Related Questions