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:
- Default Behavior (
negateis omitted orfalse): The resulting perpendicular vector is rotated 90 degrees clockwise relative to the original directional vector. For instance, a vector pointing right(1, 0)returns a vector pointing downward(0, 1). - Negated Behavior (
negateistrue): The output is inverted to{ x: vector.y, y: -vector.x }, resulting in a vector rotated 90 degrees counter-clockwise (or 270 degrees clockwise). A vector pointing right(1, 0)returns a vector pointing upward(0, -1).
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:
- Calculating Surface Normals: Finding the perpendicular plane relative to an object's trajectory.
- Applying Tangential Forces: Generating sideways steering, friction, or aerodynamic lift perpendicular to the current path of travel.
- Separation and Projection: Assisting in custom collision detection, bounding box projections, or raycasting algorithms.