Saturday, July 25, 2015

c# - How can I accurately simulate orbits in Unity?


I would like to create a space simulation with realistic gravity.


This means planets in 3d space which act as central gravity sources and multiple objects which are attracted by those planets gravity so that they orbit them in physically correct orbits (like in Kerbal Space Program, for example).


How can I implement such gravity sources with C# script?



Answer



Here is a C# script for a GravitySource component.


It requires a Collider attached to the same game object with the "Is Trigger" checkbox set. This collider represents the zone of influence of the bodies gravity. Any Rigidbodys inside of that collider will be affected.


The public property gravity needs to be set in the inspector. It represents the strength of the gravity source. The ideal value depends on the time-scale and space-scale of your simulation.


using UnityEngine;

using System.Collections;

public class GravitySource : MonoBehaviour {

public float gravity;

void OnTriggerStay(Collider other) {
Rigidbody otherRigidbody = other.gameObject.GetComponent()
if (otherRigidbody) {
Vector3 difference = this.gameObject.transform.position - other.gameObject.transform.position;


float dist = difference.magnitude;
Vector3 gravityDirection = difference.normalized;
Vector3 gravityVector = (gravityDirection * gravity) / (dist * dist) ;

otherRigidbody.AddForce(gravityVector, ForceMode.Acceleration);

}
}
}

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...