Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

standard newtonian gravity help

Discussion in 'Scripting' started by samloeschen, May 30, 2011.

  1. samloeschen

    samloeschen

    Joined:
    Mar 22, 2010
    Posts:
    268
    I'm making a top down space shooter that involves orbiting around planets at high velocities. I need to make it so that the amount of gravitational pull a planet has is translated directly to the mass of the planet and the mass of the object that it is pulling. I also need to make it so the character won't hit the planets unless they are traveling directly at them above a certain velocity. If they're below this velocity, gravitational pull will deflect their trajectory into the orbit of that planet or another planet.

    I know the standard equation for this is Fg = G (m1 * m2 ) / r^2...but as an artist I'm not sure how to get that into scripting reliably.


    Any suggestions?
     
  2. Jesse Anders

    Jesse Anders

    Joined:
    Apr 5, 2008
    Posts:
    2,857
    Your avatar is rather unsettling ;)

    If your question is simply how to convert the equation:

    Code (csharp):
    1. Fg = G (m1 * m2 ) / r^2
    To code and to apply the resultant force, then here's some completely untested C# code showing how it might be done:

    Code (csharp):
    1. void applyGravitationalForces(Rigidbody body1, Rigidbody body2, float G)
    2. {
    3.     Vector3 diff = body2.transform.position - body1.transform.position;
    4.     float r = diff.magnitude;
    5.     diff /= r;
    6.     float F = (G * body1.mass * body2.mass) / (r * r);
    7.     body1.AddForce(diff * F);
    8.     body2.AddForce(-diff * F);
    9. }
    Not sure if that's what you're looking for though.