How to Calculate Kinetic Energy in Matter.js
Calculating the kinetic energy of a body in Matter.js involves determining both its translational motion through space and its rotational motion around its center of mass. By reading built-in properties from a rigid body—specifically its mass, linear speed, moment of inertia, and angular velocity—you can compute the total kinetic energy using standard physics equations.
The Kinetic Energy Formula
In rigid-body physics, total kinetic energy (\(E_k\)) is the sum of translational kinetic energy and rotational kinetic energy:
- Translational Kinetic Energy: \(\frac{1}{2} m v^2\)
- \(m\) is the mass of the body
(
body.mass). - \(v\) is the linear speed
(
body.speedor the magnitude ofbody.velocity).
- \(m\) is the mass of the body
(
- Rotational Kinetic Energy: \(\frac{1}{2} I \omega^2\)
- \(I\) is the moment of inertia
(
body.inertia). - \(\omega\) is the angular velocity
(
body.angularVelocity).
- \(I\) is the moment of inertia
(
\[\text{Total Kinetic Energy} = \frac{1}{2} m v^2 + \frac{1}{2} I \omega^2\]
Implementation in JavaScript
You can write a helper function that takes a Matter.js
Body instance and returns its total kinetic energy in
Joules (or the arbitrary energy units of your simulation engine).
function getKineticEnergy(body) {
// Static bodies do not have kinetic energy
if (body.isStatic) {
return 0;
}
// Translational kinetic energy: 0.5 * m * v^2
const linearSpeedSquared = (body.velocity.x * body.velocity.x) + (body.velocity.y * body.velocity.y);
const translationalKE = 0.5 * body.mass * linearSpeedSquared;
// Rotational kinetic energy: 0.5 * I * w^2
const angularSpeedSquared = body.angularVelocity * body.angularVelocity;
const rotationalKE = 0.5 * body.inertia * angularSpeedSquared;
return translationalKE + rotationalKE;
}Important Considerations
body.speedvs. Velocity Components: Matter.js automatically computesbody.speedas \(\sqrt{v_x^2 + v_y^2}\). Using(body.velocity.x ** 2 + body.velocity.y ** 2)avoids unnecessary square root and re-squaring operations.- Static Bodies: Static bodies in Matter.js have
their
massandinertiaset toInfinity. Calculating the kinetic energy directly without checkingbody.isStaticwill result inNaNorInfinity. - Compound Bodies: For compound bodies formed by
parts, querying the parent body's
mass,inertia,velocity, andangularVelocitywill accurately represent the total energy of the combined system.