- Home /
Gravity within range
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);
}
Answer by DawdleDev · Jul 09, 2018 at 06:49 PM
If you want correct physics, I suggest not doing this and just decreasing the mass of the objects so that they naturally attract from further away. If you don't care whether it's physically correct or not, I suggest just changing the fixed update code to say this:
foreach (Attractor attractor in Attractors)
{
if (attractor != this && (rb.position - attractor.rb.position).magnitude <= *REACH DISTANCE*)
Attract(attractor);
}
Your answer
Follow this Question
Related Questions
optimizing Gravitacional object-to-object calculations 1 Answer
How can I apply gravity to each particle within a 'Gravity Zone' region? 0 Answers
Setting limits to my trajectory 2 Answers
pulling in objects one end, and releasing out the other 0 Answers
Ball is moving with constant velocity but not attaining same distance 0 Answers