Okay, so I have been trying to simulate a solar system in unity, and the way I’m going about it is giving me headaches. Instead of setting up fixed orbits around the sun, I have instead tried to implement a gravity system so that everything orbits the sun based on their mass and their velocity. However I’m having issues getting the velocity part to work. The mass works fine and if you press play items with large mass like the sun very quickly attracts everything within its reach, but nothing starts orbiting, it always clumps together. To try to solve this I added in the variable Velocity. I created an empty game object and parented it to the planet I’m trying to get to orbit. The purpose of this is because I want the planet to rotate on its axis, but at the same time, i need the velocity force to be applied to the planet perpendicular to the pull of the suns mass at all times. the empty game object is set to constantly face the sun, in the hopes that i can call its x axis to apply force to the planet, since the x axis of the empty game object will always be perpendicular to the suns gravitational pull. that is the theory anyways, but in practice, when I hit play, it seems that the force isn’t applied to the desired direction, and the planet ends up sling shotting off of the sun and gets flung into oblivion. Any help with this would be appreciated, I know there are far easier ways to get a planet to orbit, but for the purpose of my project, i need it to be in a free orbit based on gravity.
Here is the code I am using for this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Attractor : MonoBehaviour
{
const float G = 667.4f;
public GameObject thrustLock;
public float velocity;
public static List Attractors;
public Rigidbody rb;
void FixedUpdate()
{
foreach(Attractor attractor in Attractors)
{
if(attractor != this)
{
Attract(attractor);
}
}
}
void Update()
{
rb.AddRelativeForce(thrustLock.transform.right * velocity);
}
void OnEnable()
{
if(Attractors == null)
{
Attractors = new List();
}
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) / distance;
Vector3 force = direction.normalized * forceMagnitude;
rbToAttract.AddForce(force);
}
}