Customize Spacing in Matter.js Composites.stack

Adjusting the spacing between bodies in a Matter.Composites.stack in Matter.js is accomplished using the columnGap and rowGap parameters built directly into the stack factory method. By configuring these parameters, you can precisely control the horizontal and vertical intervals separating bodies without having to manually calculate coordinates inside the element creation callback.

Understanding the Stack Method Signature

The Matter.Composites.stack function accepts parameters in the following order:

Matter.Composites.stack(xx, yy, columns, rows, columnGap, rowGap, callback);

Implementation Example

To create a 5x5 grid of 40x40 pixel boxes with a 15-pixel horizontal gap and a 20-pixel vertical gap:

const { Composites, Bodies, World } = Matter;

const boxWidth = 40;
const boxHeight = 40;
const columnGap = 15;
const rowGap = 20;

const stack = Composites.stack(
  100, // xx: Starting X
  100, // yy: Starting Y
  5,   // columns
  5,   // rows
  columnGap,
  rowGap,
  function(x, y) {
    return Bodies.rectangle(x, y, boxWidth, boxHeight);
  }
);

World.add(engine.world, stack);

How the Spacing Calculation Works

Matter.js automatically computes the x and y coordinates passed into the callback based on the body dimensions returned during generation:

  1. For the first item, x and y start at xx and yy.
  2. For subsequent columns, Matter.js measures the width of the previously returned body, adds the specified columnGap, and offsets the x position accordingly.
  3. For subsequent rows, Matter.js uses the height of the bodies plus the rowGap to shift the y position downward.

Using Negative and Zero Gaps