Stack a cube over another dynamically

纵然是瞬间 提交于 2019-12-24 07:29:37

问题


I am working on a project in three.js, where the user can change dynamically the dimension of the objects inside it. The objects are two boxes with different dimensions and one box, should be always located on top of the other one. For instance, if the height of cube is 10, chimney.position.y should be 10. I tried different possibilities, but it is not working.

Here is a snippet of my code:

var cubeHeight = 0.1;
var boxGeometry = new THREE.BoxGeometry(0.1, cubeHeight, 0.1);
var boxMaterial = new THREE.MeshLambertMaterial({color: 0x000088});
cube = new THREE.Mesh(boxGeometry, boxMaterial);
cube.position.set(0, cubeHeight/2, 0);
scene.add(cube);

var chimneyGeometry = new THREE.BoxGeometry(5, 0.1, 5);
var chimneyMaterial = new THREE.MeshLambertMaterial({color: 0x000088});  
chimney = new THREE.Mesh(chimneyGeometry, chimneyMaterial);
chimney.position.set(0,cubeHeight,-12.5);
scene.add(chimney);

// Now the GUI panel for the interaction is defined
gui = new dat.GUI();
parameters = { 
    length: 1, height: 1, width: 1,
    tall: 1 
}

// Define the second folder which takes care of the scaling of the cube
var folder1 = gui.addFolder("House dimensions (cm)");
var cubeX = folder1.add(parameters,"length").min(1).max(2000).step(1).listen();
var cubeY = folder1.add(parameters, "height").min(1).max(2000).step(1).listen();
var cubeZ = folder1.add(parameters, "width").min(1).max(2000).step(1).listen();
var chimneyHeight = folder1.add(parameters, "tall").min(1).max(700).step(1).listen(); 
folder1.open();

 // Function taking care of the cube changes
 // cubeY has a different value to keep the solid fixed to the floor
 cubeX.onChange(function(value){cube.scale.x = value; roof.scale.x = value;});
 cubeY.onChange(function(value){cube.scale.y = value; cube.position.y = (cubeHeight * value) / 2;});
 cubeZ.onChange(function(value){cube.scale.z = value;});
 chimneyHeight.onChange(function(value){chimney.scale.y = value; chimney.position.y = ((cubeHeight * value) / 2) + cubeY;});

Do you have an idea of how to solve this issue? Thanks in advance for your answers!


回答1:


Here is one solution:

    cubeY.onChange(function(value){
        cube.scale.y = value;
        cube.position.y = (cubeHeight * value) / 2;
        chimney.position.y = (chimneyHeight * chimney.scale.y) / 2 + cube.position.y * 2
    });

    chimneyY.onChange(function(value){
        chimney.scale.y = value;
        chimney.position.y = (chimneyHeight * value) / 2 + cube.position.y * 2;
    });

and here is fiddle for it: http://jsfiddle.net/z1yd342b/

three.js r71



来源:https://stackoverflow.com/questions/29880150/stack-a-cube-over-another-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!