在three.js中着色形状的各个面

时间:2013-02-05 18:05:35

标签: javascript three.js

我正在扩展一个显示旋转立方体的简单示例,我想改变单个面部的颜色,但没有任何运气。这段代码出了什么问题?感谢

$(function(){
    var camera, scene, renderer,
    geometry, material, mesh;

    init();
    animate();

    function init() {
        scene = new THREE.Scene();
        camera = new THREE.PerspectiveCamera( 35, window.innerWidth / window.innerHeight, 1, 10000 );
        camera.position.z = 800;

        geometry = new THREE.CubeGeometry( 500, 70, 70 );

        material_1 = new THREE.MeshBasicMaterial( { 
            color: 0xff0000,
            shading: THREE.FlatShading, 
            overdraw: true 
        } );
        material_2 = new THREE.MeshBasicMaterial( { 
            color: 0x00ff00, 
            shading: THREE.FlatShading, 
            overdraw: true 
        } );
        geometry.materials = [material_1, material_2];
        geometry.faces[0].materialIndex = 0;
        geometry.faces[1].materialIndex = 1;
        geometry.faces[2].materialIndex = 0;
        geometry.faces[3].materialIndex = 1;
        geometry.faces[4].materialIndex = 0;
        geometry.faces[5].materialIndex = 1;
        mesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial() );

        scene.add( mesh );
        renderer = new THREE.CanvasRenderer();
        renderer.setClearColorHex(0x000000, 1);
        renderer.setSize( window.innerWidth, window.innerHeight );
        document.body.appendChild( renderer.domElement );
    }

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

1 个答案:

答案 0 :(得分:7)

您需要将一组材质作为参数传递给MeshFaceMaterial构造函数。

而不是:

 mesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial() );

你应该:

 mesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( geometry.materials ) );