so I'm trying to make a program that allows asteroids in a field to be attracted to each other like this: https://www.youtube.com/watch?v=iAWZwTWJmhM
I have two programs to do this, one randomly generates asteroids, the other applies gravitational force to each object. the problem is that the asteroids will get faster as they get closer until they are bullet speed and the applied forces causes them to shoot away from each other and disappear. Is there a way to make them negate their forces on contact. I tried Rigidbody.isKinematic but that makes the asteroids still instead of rotating like they would in space. ill post the code below but here are the two projects I'm using the code from. https://www.youtube.com/watch?v=Ouu3D_VHx9o https://www.youtube.com/watch?v=6rTfZ2ox2_g
Code for asteroid spawner. I added in the random scale generator.:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AsteroidFieldGenerator : MonoBehaviour
{
public Transform AsteroidPrefab;
public int fieldRadius = 50;
public int asteroidCount = 60;
public float SizeMinPercent = 1;
public float SizeMaxPercent = 100;
// Start is called before the first frame update
void Start()
{
for (int loop = 0; loop < asteroidCount; loop++)
{
Instantiate(AsteroidPrefab, Random.insideUnitSphere * fieldRadius, Quaternion.identity);
AsteroidPrefab.transform.localScale = Vector3.one * (Random.Range(SizeMinPercent, SizeMaxPercent) / 100);
}
}
// Update is called once per frame
void Update()
{
}
}
Program for applying gravity:
'''
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Attractor : MonoBehaviour
{
const float G = 667.4f;
public static List<Attractor> Attractors;
public Rigidbody rb;
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.magnitude;
if (distance == 0f)
return;
float forceMagnitude = G * (rb.mass * rbToAttract.mass) / Mathf.Pow(distance, 2);
Vector3 force = direction.normalized * forceMagnitude;
if (distance == 0)
force = force * 0;
rbToAttract.AddForce(force);
}
}
'''