This script gives an object gravity. but i want the gravity to only affect objects within a certain distance rather than from anywhere. How can i do this.
const float G = 667.4f;
public static List<Attractor> Attractors;
public Rigidbody rb;
private void FixedUpdate()
{
foreach (Attractor attractor in Attractors)
{
if (attractor != this)
Attract(attractor);
}
}
void OnEnable ()
{
if (Attractors == null)
Attractors = new List<Attractor>();
Attractors.Add(this);
}
private void OnDisable()
{
Attractors.Remove(this);
}
void Attract (Attractor objToAttract)
{
Rigidbody rbToAttract = objToAttract.rb;
Vector3 direction = rb.position - rbToAttract.position;
float distance = direction.magnitude;
float forceMagnitude = G * (rb.mass * rbToAttract.mass) / Mathf.Pow(distance, 2);
Vector3 force = direction.normalized * forceMagnitude;
rbToAttract.AddForce(force);
}