- Home /
Gravitational Object Creation for 3D Game
I want to create a gravitational object which attracts other objects when they come within its range from all direction.
What kind of code, I require to write for this purpose?
Answer by termway · Jul 01, 2019 at 05:34 PM
You need to use the gravitational force formula or an equivalent and then to compute the total force applied on your object. The simple approach would be to use Unity Physics with rigidbody attached to yours objects. Something like this (not tested) :
public Rigidbody[] rigidbodies;
Rigidbody rigidbody;
const float G = 6.67408e-11f;
void Start()
{
rigidbody = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
Vector3 totalForce = Vector3.zero;
foreach (Rigidbody rb in rigidbodies)
{
float r = Vector3.Distance(rigidbody.centerOfMass, rb.centerOfMass);
Vector3 direction = rb.centerOfMass - rigidbody.centerOfMass;
float force = rigidbody.mass * rb.mass * G / (r * r);
totalForce += direction * force;
}
rigidbody.AddForce(totalForce);
}
How rigidbodies values get filled? That you forget to mention.
You can do it manually at the beginning, just drag & drop the rigidbodies that you want interaction with. You can also use tag on yours objects with GameObject.FindGameObjectsWithTag method. You can also use a parent which contains all objects and a GameObject.GetComponentsInChildren method.