Matter.js Polygon Moment of Inertia Formula

This article explains the mathematical formula used by the Matter.js 2D physics engine to compute the moment of inertia for arbitrary polygons. By breaking down the underlying algorithm found in the engine's source code, you will learn how discrete vertex coordinates and total mass are transformed into rotational inertia about the polygon's center of mass.

Matter.js computes the moment of inertia (\(I\)) for an arbitrary polygon within its Vertices.inertia method. The calculation assumes uniform density and relies on decomposing the polygon into signed triangular sectors anchored at the origin. If the vertices are centered at the polygon's centroid, this yields the central moment of inertia directly.

The Mathematical Formula

Given an \(N\)-sided polygon defined by sequential vertices \(v_i = (x_i, y_i)\) for \(i = 0, 1, \dots, N-1\) (with cyclic wrapping such that \(v_N = v_0\)), and a total mass \(m\), Matter.js evaluates the moment of inertia using the following formula:

\[I = \frac{m}{6} \cdot \frac{\sum_{i=0}^{N-1} |x_i y_{i+1} - x_{i+1} y_i| \left( v_{i+1} \cdot v_{i+1} + v_{i+1} \cdot v_i + v_i \cdot v_i \right)}{\sum_{i=0}^{N-1} |x_i y_{i+1} - x_{i+1} y_i|}\]

Variable Definitions

\[v_{i+1} \cdot v_{i+1} + v_{i+1} \cdot v_i + v_i \cdot v_i = (x_{i+1}^2 + y_{i+1}^2) + (x_{i+1}x_i + y_{i+1}y_i) + (x_i^2 + y_i^2)\]

Derivation Context

The formula is derived from the continuous surface integral of rotational inertia for a planar shape, \(I = \rho \iint (x^2 + y^2) \, dx\,dy\), where \(\rho\) is the areal mass density.

By applying Green's theorem, the area integral over the polygon reduces to a summation of integrals over each triangular wedge with vertices at \((0,0)\), \(v_i\), and \(v_{i+1}\). For any individual triangle with vertices at the origin and vectors \(v_i, v_{i+1}\), the second moment of area about the origin is:

\[I_{\text{triangle}} = \frac{A_i}{6} \left( \|v_{i+1}\|^2 + v_{i+1} \cdot v_i + \|v_i\|^2 \right)\]

Because the total area of the polygon is \(A = \frac{1}{2} \sum |x_i y_{i+1} - x_{i+1} y_i|\), dividing the weighted numerator sum by the denominator sum normalizes the geometry by total area. Multiplying by total mass \(m\) yields the final moment of inertia.