Last active
August 21, 2018 19:40
-
-
Save 4x4notfound/5464958 to your computer and use it in GitHub Desktop.
Gravitational pull in Unity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Get all the objects in range | |
Collider[] cols = Physics.OverlapSphere(transform.position, range); | |
// Assign the first object as the nearest for now | |
Collider nearest = cols[0]; | |
// Loop through objects | |
foreach (Collider c in cols) | |
{ | |
// Get the current objects rigidbody | |
Rigidbody rb = c.attachedRigidbody; | |
// Get the force between the objects | |
Vector3 offset = transform.position - c.transform.position; | |
// Get the square of the force (distance) | |
float sqmag = offset.sqrMagnitude; | |
// if this object is closer | |
if (rigidbody != rb && sqmag < nearest.transform.position.sqrMagnitude && rb != rigidbody && rb.tag != "Player") | |
{ | |
nearest = c; //assign this as the new nearest | |
} | |
} | |
// double check that we are not refering to self | |
if (nearest.rigidbody != rigidbody) | |
{ | |
//get the force of the nearest object | |
Vector3 force = transform.position - nearest.transform.position; | |
// Normalize the force | |
force.Normalize(); | |
// Apply the force | |
rigidbody.AddForce(GravityConstant * force * rigidbody.mass * nearest.rigidbody.mass / force.sqrMagnitude); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment