- Home /
Calculating the Trajectory of Planetary Bodies
Hi,
I have gotten planetary gravity working well and how I want it, but I can't figure out how to predict trajectories of objects. I've seen other examples of how to do it with using standard gravity. Here is the script that goes on every object that will attract one another.
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Transform))]
public class NewtonBody : MonoBehaviour {
public Transform _transform;
public float mass = 1f;
public Vector3 velocity = Vector3.zero;
public Vector3 initialForwardSpeed = Vector3.zero;
void Awake() {
_transform = GetComponent<Transform>();
}
}
This is the script that actually calculates the pull between all objects that have the script above.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Newton : MonoBehaviour {
// Gravitational constant
public float g = 0.01f;
static List<NewtonBody> bodies;
static Vector3 acceleration;
static Vector3 direction;
static float fixedDeltaTime;
static Newton self;
void Start() {
self = this;
NewtonSetup();
}
void FixedUpdate() {
foreach(NewtonBody body in bodies) {
NewtonUpdate(body);
}
}
static void NewtonSetup() {
fixedDeltaTime = Time.fixedDeltaTime;
bodies = new List<NewtonBody>();
bodies.AddRange(FindObjectsOfType(typeof(NewtonBody)) as NewtonBody[]);
Debug.Log("There are probably " + bodies.Count + " Newton bodies in space (±42).");
foreach(NewtonBody body in bodies) {
body.velocity = body._transform.TransformDirection(body.initialForwardSpeed);
}
}
static void NewtonUpdate(NewtonBody body) {
acceleration = Vector3.zero;
foreach(NewtonBody otherBody in bodies) {
if(body == otherBody) continue;
direction = (otherBody._transform.position - body._transform.position);
acceleration += self.g * (direction.normalized * otherBody.mass) / direction.sqrMagnitude;
}
body.velocity += acceleration * fixedDeltaTime;
body._transform.position += body.velocity * fixedDeltaTime;
}
}
If anyone has any ideas/pointers on how to create a trajectory with the code above, I would be very grateful.
Thanks
I have been pulling my hair to find a script that will do this. Thank you! Works like a charm. The only thing that needs to be changed is "direction" which just needs to be set to a Vector3. Other than that, perfect!
(And, for anyone who had the same issue as me, don't forget to change "public float g = 0.01f;" to something higher than 0.01 so that gravity actually has a chance. The actual constant is written as 6.673e-11f)
By the way, I'm trying to figure out a way to have a character walk on the surface of the planets, got any idea of how to implement this?