Place random sized balls next in a row next to each other

Hello :vulcan_salute:

I’m trying this code to set balls in the row next to each other:

  for (let i = 0; i < objects.length; i++) {
  const object = objects[i]
    // getting size
    const ballBoundingBox = new THREE.Box3().setFromObject(object)
    const ballSize = ballBoundingBox.getSize(new THREE.Vector3())
    const radius = ballSize.x
    // setting new position
    const x = rowWidth = rowWidth + radius
    object.position.set(x, 0, 0)

And that works file when all balls are in the same size, but if I set random ball sizes:
object.scale.setScalar(Math.random() * 0.05 + 0.05)

Balls start to overlap each other, and gaps appear. I can’t figure out what’s the problem. Please help :pray:

Attaching screenshots:

And pen:

The distance between different radius spheres standing next to each other is equal to the sum of their radiuses. You need to place a sphere one radius away to the right of the marker, advance the marker by the sphere diameter, calculate the next sphere and place it by its own radius away from the marker.

I didn’t rename your variables but what you call ‘radius’ is actually a diameter since it’s returned from the bounding box of a sphere.

1 Like

Thank you! That worked great.

Seems like I need to refresh my geometry knowledge, if I want to work with ThreeJS :slight_smile:

1 Like