Search Unity

Gravity Immediately Attracts

Discussion in 'Scripting' started by OdyseeGames, Aug 8, 2020.

  1. OdyseeGames

    OdyseeGames

    Joined:
    Jun 24, 2020
    Posts:
    25
    Hello,

    I watched Brackeys gravity video and followed his project step by step. But, when I go to play it in the Unity editor window, the objects attract to each other immediately and then they go flying off somewhere. I've tried playing with the Rigidbody Mass, the distance between the objects within the scene, and it is always the same thing. Any help would be greatly appreciated with trying to stop the objects from immediately attracting to one another and having them attract to one another like they do in the tutorial video.


    Code (CSharp):
    1. using System.Collections.Generic;
    2. using UnityEngine;
    3.  
    4. public class Attractor : MonoBehaviour
    5. {
    6.     const float G = 667.4f;
    7.  
    8.     public static List<Attractor> Attractors;
    9.  
    10.     public Rigidbody rb;
    11.  
    12.     private void FixedUpdate()
    13.     {
    14.         foreach (Attractor attractor in Attractors)
    15.         {
    16.            if (attractor != this)
    17.             Attract(attractor);
    18.         }
    19.     }
    20.  
    21.     void OnEnable()
    22.     {
    23.         if (Attractors == null)
    24.             Attractors = new List<Attractor>();
    25.        
    26.         Attractors.Add(this);
    27.     }
    28.  
    29.     void OnDisable()
    30.     {
    31.         Attractors.Remove(this);
    32.     }
    33.  
    34.     void Attract(Attractor objToAttract)
    35.     {
    36.         Rigidbody rbToAttract = objToAttract.rb;
    37.  
    38.        Vector3 direction = rb.position = rbToAttract.position;
    39.         float distance = direction.sqrMagnitude;
    40.  
    41.         if (distance == 0f)
    42.             return;
    43.  
    44.         float forceMagnitude = G * (rb.mass * rbToAttract.mass) / Mathf.Pow(distance, 2);
    45.         Vector3 force = direction.normalized * forceMagnitude;
    46.  
    47.         rbToAttract.AddForce(force);
    48.     }
    49. }
    50.  
     
  2. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    Your directional vector calculation is likely meant to be rb.position - rbToAttract.position not rb.position = rbToAttract.position and why is your gravity float so high? Are these meant to be planets that are vast distances from each other?
     
  3. OdyseeGames

    OdyseeGames

    Joined:
    Jun 24, 2020
    Posts:
    25

    Yup, that was exactly it! Thanks! And I take it I can have objects repel each other by changing that to a +.