# Math help with centering multiple objects with gaps inbetween

I’m trying to create some code that populates the inside of a box with multiple boxes, these boxes are positioned perfectly when there is no gap (gap = 0) however when I introduce a gap then they are no longer centre positioned. Here is my pseudo function (basically I’ve just stripped out a lot of non-relevant stuff)

``````function boxSplitter(box:CustomBox)
{
let position = 0
let allGapsCombined:number
let gap:number
const amountOfBoxes:number = 7
const evenAmountOfBoxes:number = 0
const bb = new THREE.Box3().setFromObject(box.threeGroup);
let size = bb.getSize(new THREE.Vector3());
let gapInsideParentBox = 3
const width:number =  size.x - gapInsideParentBox
let sizeOfContainerDimension:number = width
allGapsCombined = 3
sizeOfContainerDimension -= allGapsCombined
gap = allGapsCombined / (amountOfBoxes-1)
let sizeOfBlocksInPercentageArray:Array<number> = calcBoxes(evenAmountOfBoxes, amountOfBoxes)

for (let index = 0; index < amountOfBoxes; index++) {
const currentUnitSize = (sizeOfContainerDimension * sizeOfBlocksInPercentageArray[index]/100)
let innerBox = makeBox(insideBox, 3, 0) as CustomBox
let placement:number = position - (sizeOfContainerDimension/2 - currentUnitSize/2)-gap;
innerBox.position.x = placement
position += currentUnitSize + gap
}
}
``````

with no gap, boxes are perfectly centered

with allGapsCombined = 4

for some reason when it’s three blocks it centres again perfectly

But with any other number of blocks, it doesn’t work

Any idea what I’m doing wrong?

This is an example of how to equidistribute objects inside a box (re-run a few times to get diff number of objects):

maybe not exactly what you need but it gives you the math for these kinds of tasks.

1 Like

Thanks! gonna try make this work with my code