- Home /
Question by
Tekman03 · Mar 22, 2019 at 08:32 PM ·
c#physicsgravityfixedupdateorder-of-execution
Gravity Simulator - Script execution order
Hi there,
I have been trying to build a gravity simulator for use at my school. I followed the Brackeys tutorial on this and it works great for two objects; however, as soon as I add a third object to the scene, it starts behaving strangely. With three object placed equidistantly and of the same mass, they should all attract at the same rate, meaning the middle object should stay stationary and the other two should end up at the same position as each other (but negative).
I am assuming that this issue is something to do with the execution of the script:
void FixedUpdate()
{
foreach (Gravity attractor in Attractors)
{
if (attractor != this)
Attract(attractor);
}
}
void Attract(Gravity objToAttract)
{
Rigidbody rbToAttract = objToAttract.rb;
Vector3 direction = rb.position - rbToAttract.position;
float distance = direction.magnitude;
if (distance == 0f)
return;
float forceMagnitude = G * (rb.mass * rbToAttract.mass) / Mathf.Pow(distance, 2);
Vector3 force = direction.normalized * forceMagnitude;
rbToAttract.AddForce(force, ForceMode.Acceleration);
}
So, I was wondering if there was anyway in Unity to simultaneously calculate the forces (or fake the program into calculating the time through the frame?...)
Many thanks Craig
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612194107im_/https://answers.unity.com/themes/thub/images/avi.jpg)