Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

how to replicate gravity on a miniature planet

Discussion in 'Physics' started by SkinnyDinner, Nov 16, 2020.

  1. SkinnyDinner

    SkinnyDinner

    Joined:
    Feb 13, 2016
    Posts:
    8
    I'm making a game with a very small planet. I want this planet's gravity to perfectly reflect actual laws of physics, other than the fact that the planet shouldn't move. What I've got might be fine, but I'm unsure of whether I should use "time.deltatime" or normalize the direction and stuff like that. It would be great if someone could guide me in the right direction.

    Code (CSharp):
    1. public class Gravity : MonoBehaviour
    2. {
    3.  
    4.     public float gravityForce = 10;
    5.  
    6.     void FixedUpdate()
    7.     {
    8.         Rigidbody[] rigBods = FindObjectsOfType<Rigidbody>();
    9.         foreach (var i in rigBods)
    10.         {
    11.             i.useGravity = false;
    12.  
    13.             i.velocity += i.mass * (transform.position - i.position).normalized * gravityForce;
    14.         }
    15.     }
    16. }
     
  2. tjmaul

    tjmaul

    Joined:
    Aug 29, 2018
    Posts:
    464
    :D

    you're off to a good start I guess, but rather than changing the velocity, just add an acceleration to the rigidbody so you don't have to worry about Time.deltaTime, Time.fixedDeltatime, Time.unscaledDeltaTime, Time.doubleTime, Time.hammerTime:

    i.AddForce(transform.position - i.position).normalized * gravityForce, ForceMode.Acceleration);

    However, the gravity should get less, the further away from the planet you go. But this might already be overkill.
     
  3. SkinnyDinner

    SkinnyDinner

    Joined:
    Feb 13, 2016
    Posts:
    8
    Thankyou so much i cant believe i missed this notification by a whole week
     
    tjmaul likes this.