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.
using System.Collections.Generic;
using UnityEngine;
public class Attractor : MonoBehaviour
{
const float G = 667.4f;
public static List<Attractor> Attractors;
public Rigidbody rb;
private void FixedUpdate()
{
foreach (Attractor attractor in Attractors)
{
if (attractor != this)
Attract(attractor);
}
}
void OnEnable()
{
if (Attractors == null)
Attractors = new List<Attractor>();
Attractors.Add(this);
}
void OnDisable()
{
Attractors.Remove(this);
}
void Attract(Attractor objToAttract)
{
Rigidbody rbToAttract = objToAttract.rb;
Vector3 direction = rb.position = rbToAttract.position;
float distance = direction.sqrMagnitude;
if (distance == 0f)
return;
float forceMagnitude = G * (rb.mass * rbToAttract.mass) / Mathf.Pow(distance, 2);
Vector3 force = direction.normalized * forceMagnitude;
rbToAttract.AddForce(force);
}
}