using System.Collections.Generic;
using UnityEngine;

public class EnergyTracker : MonoBehaviour
{
	public static float totalEnergy;

	public List<Rigidbody2D> bodies;

	private float next=0;

    void Update()
    {
		if (Input.GetKey(KeyCode.Escape))
		{
			Application.Quit();
		}

		if (Time.time > next)
		{
			UpdateEnergyDisplay();
			next = Time.time + .300f;
		}
	}

	private void UpdateEnergyDisplay()
	{
		float totalKinetic = 0;
		float totalPotential = 0;

		foreach (Rigidbody2D rb in bodies)
		{
			totalKinetic += 0.5f * rb.mass * Mathf.Pow(rb.velocity.magnitude, 2);  // 1/2 mV^2

			float g = Mathf.Abs(Physics2D.gravity.y * rb.gravityScale);
			totalPotential += rb.mass * g * rb.transform.position.y;
		}

		totalEnergy = Mathf.Round((totalKinetic + totalPotential)/100f);

	}
}
