Skip to content

Instantly share code, notes, and snippets.

@maurerbot
Last active August 21, 2018 19:40
Show Gist options
  • Save maurerbot/5464958 to your computer and use it in GitHub Desktop.
Save maurerbot/5464958 to your computer and use it in GitHub Desktop.
Gravitational pull in Unity
// 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