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:

  1. Translational Kinetic Energy: \(\frac{1}{2} m v^2\)
    • \(m\) is the mass of the body (body.mass).
    • \(v\) is the linear speed (body.speed or the magnitude of body.velocity).
  2. Rotational Kinetic Energy: \(\frac{1}{2} I \omega^2\)
    • \(I\) is the moment of inertia (body.inertia).
    • \(\omega\) is the angular velocity (body.angularVelocity).

\[\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