How Matter.Bounds.shift Works in Matter.js

This article explains how the Matter.Bounds.shift method relocates an Axis-Aligned Bounding Box (AABB) to an absolute target coordinate in Matter.js. You will learn the underlying vector math used to translate the bounding coordinates, how the method preserves the dimensions of the box, and how to implement it correctly in your physics simulations.

Understanding the AABB Structure

In Matter.js, an AABB is represented by a Bounds object. This object defines a rectangular area aligned with the coordinate axes, composed of two 2D vectors:

The width of the bounding box is max.x - min.x, and the height is max.y - min.y.

The Mechanics of Matter.Bounds.shift

The Matter.Bounds.shift(bounds, position) function moves the entire bounding box so that its upper-left anchor (bounds.min) matches the absolute target coordinate provided in the position argument ({ x, y }).

Instead of redefining the entire shape, the function calculates the displacement needed and translates both the min and max vertices by that displacement.

Mathematical Implementation

Under the hood, the operation follows these specific steps:

  1. Calculate the Delta: The function computes the difference between the target position and the current minimum coordinate: \[\Delta x = \text{position.x} - \text{bounds.min.x}\] \[\Delta y = \text{position.y} - \text{bounds.min.y}\]

  2. Translate the Minimum Vector: The delta is added to the minimum bounds: \[\text{bounds.min.x} = \text{bounds.min.x} + \Delta x = \text{position.x}\] \[\text{bounds.min.y} = \text{bounds.min.y} + \Delta y = \text{position.y}\]

  3. Translate the Maximum Vector: The exact same delta is added to the maximum bounds: \[\text{bounds.max.x} = \text{bounds.max.x} + \Delta x\] \[\text{bounds.max.y} = \text{bounds.max.y} + \Delta y\]

Because the identical vector offset \((\Delta x, \Delta y)\) is applied to both corners, the width and height of the bounding box remain unchanged while its origin is snapped directly to the absolute target.

Code Example

// Define a bounding box
const bounds = {
    min: { x: 50, y: 50 },
    max: { x: 150, y: 100 } // Width: 100, Height: 50
};

// Define the absolute target position
const targetPosition = { x: 300, y: 400 };

// Shift the bounds to the absolute coordinate
Matter.Bounds.shift(bounds, targetPosition);

console.log(bounds.min); // Output: { x: 300, y: 400 }
console.log(bounds.max); // Output: { x: 400, y: 450 }

Important Considerations