如何使用Three.js更改CubeGeometry的颜色?

时间:2014-11-22 05:27:39

标签: three.js

请注意,我需要在创建之后更改它的颜色。我可以根据原始创建一个新的立方体,但我真的不愿意这样做。在我的用例中,有许多多维数据集在所有地方都有引用,所有更新它们都会很痛苦。此外,他们会经常改变颜色。

必须有更好的方法来做到这一点吗?

var startColours  = [0x0000FF, 0x00FF00, 0xFF0000, 0x00FFFF, 0xFF00FF, 0xFFFF00];
var changeColours = [0x000000, 0x000000, 0x808080, 0x808080, 0xFFFFFF, 0xFFFFFF];
var material = new THREE.MeshLambertMaterial( 
    { color: 0xFFFFFF, shading: THREE.FlatShading, vertexColors: THREE.VertexColors });

var setColours = function(geometry, colours) {
    for (var i = 0; i < 6; i++) {
        geometry.faces[i].color.setHex(colours[i]);
    }
}

var geometry = new THREE.CubeGeometry(1.0, 1.0, 1.0);
setColours(geometry, startColours);
var cubeMesh = new THREE.Mesh(geometry, material);
scene.add(cubeMesh);

// Try and change the colour after 2 seconds.
setTimeout("attempt2()", 2000);

function attempt1() {
    // Do the obvious.
    setColours(geometry, changeColours);
    // Doesn't work - no errors, but the cube just doesn't change colour.
}

function attempt2() {
    setColours(geometry, changeColours);

    scene.remove(cubeMesh);
    // Create a new mesh with a *clone* of the geometry and material of the original.
    var newCubeMesh = new THREE.Mesh(cubeMesh.geometry.clone(), cubeMesh.material);
    scene.add(newCubeMesh);
    // Does work - but having to create a completely new Mesh object is pants.
}

1 个答案:

答案 0 :(得分:2)

我会使用MeshFaceMaterial

选中此fiddle

function setColours() {
  for (var i = 0; i < 6; i++) {
    box.material.materials[i].color.setHex(changeColours[i]);
  }
}

var startMaterials = [];
for(var i = 0; i < 6; i++){
  startMaterials.push(new THREE.MeshLambertMaterial({color: startColours[i]}));
}
var material = new THREE.MeshFaceMaterial(startMaterials);

var geometry = new THREE.BoxGeometry(50, 40, 20, 2, 2, 2);

box = new THREE.Mesh(geometry, material);
scene.add(box);

setTimeout(setColours, 3000);