What is energy?
Well, this question could be the topic of a book in its own right, and is well beyond my capabilities to describle accurately. Suffice to say that energy comes in many forms including: potential, kinetic, thermal, electrical, and many more. A more strict definition of energy is that it represents the capacity of a thing to do work. One of the defining characteristics of energy though, is that in any closed system the total amount of energy never changes. It may be converted from one form to another, or transferred among different parts of the closed system, but it is never created or destroyed.
For our colliding ball simulation, we are only concerned with kinetic energy.
In the case of kinetic energy, it is calculated as half of the mass of the moving body multiplied by the velocity squared. That is:
The total energy of the system is just the sum of the energy of each individual part of the system. And as energy is a scalar value, we just add up the numbers and we are done.
Now we can add properties to our Ball class to represent its mass and energy. For the mass, we will just assume that each ball is really a flat disc with uniform density. This allows us to use the area of the ball as a proxy value for its mass. Remembering the formula for the area of a circle is:
For calculating energy we have to remember that the velocity is a vector value, so we need to use the mag() function to get the (scalar) magnitude of the velocity.
So we can modify our Ball class to include the mass and energy. The mass of a ball never changes so we can create a property in the constructor for that. But the velocity of a ball will change after a collision, so we create a function to calculate it when needed.
class Ball {
constructor(x, y, vx, vy, r) {
this.pos = createVector(x, y);
this.vel = createVector(vx, vy);
this.r = r;
this.mass = PI * sq(r); // calculate once
}
energy() {
return 0.5 * this.mass * sq(this.vel.mag()); // calculate when needed
}
...
}
Now we modify our simulation to display the energy of each ball as well as the total energy of the system. The balls are labelled so we can see the energy of each. We also show the total energy of the system. At the moment none of these values are changing because we are not handling the collisions, but once we do we expect to see the energy of each ball to change after a collision, but the total energy should remain the same.
Note that the energy of a ball does not depend on which direction it is travelling in. That is, it is never negative.