So recently I had the craving to try and create world scapes revolving around gravitational pull, so I stumbled upon this youtube video (Coding Adventure: Solar System - YouTube) that did a great job explaining everything for me and gave me a sample code:
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using UnityEngine;
public class PlanetBody : MonoBehaviour
{
public float mass;
public float radius;
public Vector3 initialVelocity;
Vector3 currentVelocity;
void Awake ()
{
currentVelocity = initialVelocity;
}
public void UpdateVelocity(PlanetBody[] allBodies, float timeStep)
{
foreach (var otherBody in allBodies)
{
if (otherBody != this)
{
float sqrDst = (otherBody.GetComponent<Rigidbody>().position - GetComponent<Rigidbody>().position).sqrMagnitude;
Vector3 forceDir = (otherBody.GetComponent<Rigidbody>().position - GetComponent<Rigidbody>().position).normalized;
Vector3 force = forceDir * Universe.gravitationalConstant * mass * otherBody.mass / sqrDst;
Vector3 acceleration = force / mass;
currentVelocity += acceleration * timeStep;
}
}
}
public void UpdatePosition (float timeStep)
{
GetComponent<Rigidbody>().position += currentVelocity * timeStep;
}
}
Now this was all well and good, until I attached it to a sphere (or any other object) and unity kept saying that Universe was used in the wrong context.
Could anybody tell me the right context or how to fix this issue?
Thanks in advance