# Problem with calculating potential and kinetic energy

Hello everyone. I need to calculate the mechanical energy of orbiting body , which is a sum of kinetic and potential energy. Mechanical energy should be constant, but for some reason, it isn’t.

This is my problem. I don’t know why, but the mechanical energy changes, when the object is moving closer/farther from the influencer. I tried calculating everything on double precision numbers, but it didn’t work.

``````public class OrbitingBody : MonoBehaviour {

Rigidbody influencer;
Rigidbody rigidbody;
public float mechanicalEnergy;
public float gravityConstant;

void Start () {
influencer = FindObjectOfType<Influencer>().GetComponent<Rigidbody>();
rigidbody = GetComponent<Rigidbody>();
}

void FixedUpdate () {
mechanicalEnergy = Energy(influencer);
}

float Energy(Rigidbody other)
{
float Ek = rigidbody.mass * rigidbody.velocity.sqrMagnitude / 2; // kinetic energy
float Ep = -gravityConstant * rigidbody.mass * other.mass / (other.transform.position - transform.position).magnitude; // potential energy

return Ek+Ep; // mechanical energy of an object;
}}
``````

}

``````public class Influencer : MonoBehaviour {

Rigidbody[] rigidbodies;
Rigidbody rigidbody;
public float gravityConstant;

void Start () {
rigidbodies = FindObjectsOfType<Rigidbody>() as Rigidbody[];
rigidbody = GetComponent<Rigidbody>();
}

void FixedUpdate()
{
foreach (Rigidbody rigid in rigidbodies)
{
if (rigidbody != rigid)
{
Vector3 dir = rigid.transform.position - transform.position;
rigid.velocity += -dir.normalized * gravityConstant * rigidbody.mass / dir.sqrMagnitude * (Time.fixedDeltaTime);

}
}
}
}
``````

I have the same problem with a simple bouncing ball:
http://gamebucket.io/game/7817e417-baa5-4e8b-9d54-10457d010770