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);xx: The initial horizontal coordinate for the top-left of the entire grid.yy: The initial vertical coordinate for the top-left of the entire grid.columns: The total number of columns to generate.rows: The total number of rows to generate.columnGap: The horizontal space (in pixels) added between adjacent columns.rowGap: The vertical space (in pixels) added between adjacent rows.callback: A function returning the body to place at each calculated(x, y)coordinate.
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:
- For the first item,
xandystart atxxandyy. - For subsequent columns, Matter.js measures the width of the
previously returned body, adds the specified
columnGap, and offsets thexposition accordingly. - For subsequent rows, Matter.js uses the height of the bodies plus
the
rowGapto shift theyposition downward.
Using Negative and Zero Gaps
- Zero Spacing (
0): SettingcolumnGaporrowGapto0places adjacent bodies directly in contact edge-to-edge. - Negative Values: Using negative values causes bodies to overlap, which is useful when assembling interlocking geometry or welded composite structures with constraints.