Search Unity

Gravity Simulation always pulls objects toward a single point

Discussion in 'Physics' started by Littlelumos, May 7, 2019.

  1. Littlelumos

    Littlelumos

    Joined:
    May 7, 2019
    Posts:
    1
    I am trying to simulate gravity for a game. I am testing my gravity system using a sphere like a planet and cubes, to test the gravity, but all of the cubes accumulate towards the horizontal centre of the sphere. Is there any way I can solve this as it makes it less realistic?

    This is the code that I have attached to the sphere (planet):
    Code (CSharp):
    1. public float pullRadius;
    2.     public float pullForce;
    3.  
    4.     public void FixedUpdate()
    5.     {
    6.         foreach (Collider coll in Physics.OverlapSphere(transform.position, pullRadius))
    7.         {
    8.             if (coll != this)
    9.             {
    10.                 Vector3 forceDirection = transform.position - coll.transform.position;
    11.                 coll.transform.Translate(forceDirection.normalized * pullForce * Time.fixedDeltaTime);
    12.             }
    13.         }
    14.     }
    upload_2019-5-7_22-10-21.png
    Thanks.
     
  2. Hyblademin

    Hyblademin

    Joined:
    Oct 14, 2013
    Posts:
    725
    I'm not totally sure what you mean by this. The picture doesn't seem to show any accumulation, since there's only one cube in it. Could you elaborate a bit?

    I did notice something odd, though:

    Code (CSharp):
    1. if (coll != this)
    I'm pretty sure that this will always evaluate to true, since this isn't even a Collider. It looks like you're trying to avoid the attractive body applying gravity to itself, which could be done like this:

    Code (CSharp):
    1. thisCollider = GetComponent<Collider>();
    2.  
    3. //...
    4.  
    5. if (coll != thisCollider)
    6. {
    7.     //...
    8. }
    On the other hand, applying gravity to itself would always give a 0 vector, so it wouldn't have any effect. I'm not sure whether it's actually worth screening self-gravitation, because there might be more overhead when running GetComponent depending on how you use it.
     
    Last edited: May 8, 2019
    Joe-Censored likes this.