Search code examples
animationthree.jsmesh

How to change width of CubeGeometry with Three.js?


I have a CubeGeometry and a mesh, and I don't know how to change the width (or height but I can change x, y and z though). Here is a snippet of what I have right now:

const geometry = new THREE.CubeGeometry( 200, 200, 200 );
const material = new THREE.MeshBasicMaterial( { color: 0xff0000, wireframe: true } );
const mesh = new THREE.Mesh( geometry, material );
// WebGL renderer here

function render(){
    mesh.rotation.x += 0.01;
    mesh.rotation.y += 0.02;
    renderer.render( scene, camera );
}

function changeStuff(){
    mesh.geometry.width = 500; //Doesn't work.
    mesh.width = 500; // Doesn't work.
    geometry.width = 500; //Doesn't work.
    mesh.position.x = 500// Works!!

    render();
}

Thanks!

EDIT

Found a solution:

mesh.scale.x = 500;

Solution

  • Just to complete comment and solution from question (and have an answer present with example code):

    // create a cube, 1 unit for width, height, depth
    var geometry = new THREE.CubeGeometry(1,1,1);
    
    // each cube side gets another color
    var cubeMaterials = [ 
        new THREE.MeshBasicMaterial({color:0x33AA55, transparent:true, opacity:0.8}),
        new THREE.MeshBasicMaterial({color:0x55CC00, transparent:true, opacity:0.8}), 
        new THREE.MeshBasicMaterial({color:0x000000, transparent:true, opacity:0.8}),
        new THREE.MeshBasicMaterial({color:0x000000, transparent:true, opacity:0.8}), 
        new THREE.MeshBasicMaterial({color:0x0000FF, transparent:true, opacity:0.8}), 
        new THREE.MeshBasicMaterial({color:0x5555AA, transparent:true, opacity:0.8}), 
    ]; 
    // create a MeshFaceMaterial, allows cube to have different materials on each face 
    var cubeMaterial = new THREE.MeshFaceMaterial(cubeMaterials); 
    var cube = new THREE.Mesh(geometry, cubeMaterial);
    
    cube.position.set(0,0,0);
    scene.add( cube );
    cube.scale.x = 2.5; // SCALE
    cube.scale.y = 2.5; // SCALE
    cube.scale.z = 2.5; // SCALE
    

    A slightly advanced, dynamic example (still the same scaling) implemented here: