Understanding Matter.Vector.perp in Matter.js

This article explains the behavior and output of the Matter.Vector.perp function in the Matter.js 2D physics engine. When supplied with a directional motion vector, Matter.Vector.perp calculates and returns a perpendicular vector (also known as a normal vector) that forms a 90-degree angle to the original input. Below, we break down the underlying mathematical formula, the resulting directional orientation in 2D canvas space, and the effect on vector magnitude.

Mathematical Operation

The Matter.Vector.perp function takes an input vector and an optional boolean negate parameter. The underlying implementation evaluates as follows:

Vector.perp = function(vector, negate) {
    negate = negate === true ? -1 : 1;
    return { x: negate * -vector.y, y: negate * vector.x };
};

When given a vector { x, y }, the function swaps the coordinates, negates the original y-component, and assigns it to x, while assigning the original x-component to y.

Directional Behavior

In standard 2D canvas and screen coordinates—where the x-axis points to the right and the y-axis points downward:

Impact on Magnitude

Matter.Vector.perp does not normalize the vector. The returned vector retains the exact same magnitude (length) as the original directional motion vector. If the input is a velocity vector with a magnitude of 15 units per frame, the returned perpendicular vector will also have a magnitude of 15 units per frame. To convert the result into a unit normal vector, it must be passed through Matter.Vector.normalise.

Common Use Cases

In Matter.js simulations, passing a directional motion vector into Matter.Vector.perp is commonly used for: