Explode or move meshes away from center

1k Views Asked by At

I am trying to move all the meshes ,of which the loaded obj file is made of, away from each other so that user can see all the meshes.

I am trying to mimic the following example

Demo

Go to the link click on explode icon in the UI tray and move the slider.

What Have I done So Far I have access to all the meshes of the model So I can apply any function on them. So far I have looped through them and gave them random position vector.

It works fine and the whole model explodes so that every mesh is separately visible.

The Problem

By giving random position vector they obviously move to random place. I want to move them exactly like the shared link. Any help would be appreciated. I am new to this awesome threejs and I would really love to learn more. Thanks in Advance

Edit Example Code

    function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}
for(var i = 0; i < mainStand.children.length; i++)
{
    pos1 = getRandomArbitrary(1 , 2);
    pos2 = getRandomArbitrary(1 , 2);
    pos3 = getRandomArbitrary(1 , 2);
    mainStand.children[i].position.set(pos1 , pos2 , pos3);
}

Where mainStand is the loaded obj Model

1

There are 1 best solutions below

6
Holger Ludvigsen On

What you want to do is to move every mesh away from the center position. This is done by calculating the vector between the mesh position and the center, and then move the mesh along this direction:

var center = new THREE.Vector3(0, 0, 0);
var distanceToMove = 0.1;

for (var i = 0; i < mainStand.children.length; i++) {
    var meshPosition = mainStand.children[i].position;

    var direction = meshPosition.clone().sub(center).normalize();

    var moveThisFar = direction.clone().multiplyScalar(distanceToMove);

    mainStand.children[i].position.add(moveThisFar);
}