Bala Bala - 2 months ago 15
Javascript Question

How to place 3d box inside another 3d box using three.js?

I am working on cargo management project. I need to render the packing order in 3d image, I am beginner to use THREE.js.
I have the positions (x,y,z axis) and size of the objects inside the container and container size. Now I need to render in 3d image.

I learned to render the container and objects separately, but don't know how to place the objects inside the container.

Please help me out to learn how to do this.

Here I tried something out like this.

init();
animate();

function init() {

var aspect = window.innerWidth / window.innerHeight;
camera = new THREE.PerspectiveCamera(55, innerWidth / innerHeight, 1, 6000);
camera.position.x = radius * Math.sin(THREE.Math.degToRad(theta));
camera.position.y = radius * Math.sin(THREE.Math.degToRad(theta));
camera.position.z = radius * Math.cos(THREE.Math.degToRad(theta));
scene.add(camera);

var geometry = new THREE.BoxBufferGeometry(2000, 2150, 5600, 1, 1, 1);
var material = new THREE.MeshPhongMaterial({ color: 0x000000, wireframe:true });

container = new THREE.Mesh(geometry, material);
container.position.x = 100;
container.position.y = 100;
container.position.z = 100;
container.scale.x = 2000;
container.scale.y = 2150;
container.scale.z = 5600;
scene.add(container);
var geometry = new THREE.BoxBufferGeometry(20, 20, 20);

for (var i = 0; i < 20; i++) {
var object = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({ color: Math.random() * 0xffffff }));
object.position.x = Math.random() * 800 - 400;
object.position.y = Math.random() * 800 - 400;
object.position.z = Math.random() * 800 - 400;
object.scale.x = Math.random() + 5;
object.scale.y = Math.random() + 5;
object.scale.z = Math.random() + 5;
scene.add(object);
container.add(object);
}
}

function animate()
{
renderer.render(scene, camera);
}


But it shows no result and no error.

Answer

You have to add the objects as the child of the container and then set the position of the objects.

// first add the container in the scene
var geometry = new THREE.BoxGeometry(container_width, container_height, container_depth);
var material = new THREE.MeshBasicMaterial( {color: 0x00ff00} );
var container = new THREE.Mesh(geometry, material);
scene.add(container);

// then add objects as the child of container
var geometry_obj = new THREE.BoxGeometry(object_width, object_height, object_depth);
var material_obj = new THREE.MeshBasicMaterial( {color: 0x00ff00} );
var object = new THREE.Mesh(geometry_obj, material_obj);
// you can set the object's position in the container
object.position.set(object_position.x, object_position.y, object_position.z)
container.add(object);