在运行时添加灯光:材料未更新?

时间:2014-10-28 14:32:46

标签: javascript three.js

当我在运行时添加一个点时,没有任何反应。我必须更改对象的材质以查看修改对象上的灯光。

我添加了MyMaterial.needsUpdate = true;:它是默认设置,不会改变任何内容。

我用平面物体(PlaneGeometry + MeshPhongMaterial)做了一个简单的测试 当我按下“L”键时,我添加一个SpotLight ==>没有任何反应 然后,当我按下“M”键时,我将新材料分配给平面==>我看到了聚光灯。

我错过了一些东西,但我不知道是什么......

我使用three.js r69

WebGLRenderer

renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setClearColor(0xffffff, 1);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMapEnabled = true;
renderer.shadowMapType = THREE.PCFSoftShadowMap;
renderer.shadowMapWidth = 1024;
renderer.shadowMapHeight = 1024;

飞机

var planeGeometry = new THREE.PlaneGeometry(60, 20);
var planeMaterial = new THREE.MeshPhongMaterial({ color: 0xffffff });
planeMaterial.side = THREE.DoubleSide;
planeMaterial.needsUpdate = true;
plane = new THREE.Mesh(planeGeometry, planeMaterial);
plane.rotation.set(Math.PI / 2.0, 0, 0);
plane.receiveShadow = true;
plane.castShadow = true;
scene.add(plane);

关键操作(使用THREEx.KeyboardState.js):

function updateKey() {
    // Add light
    if (keyboard.pressed("L")) {

        var spotLight = new THREE.SpotLight(0xffffff, 1.0, 0.0);
        spotLight.position.set(0, 15, 0);
        spotLight.angle = 1.39;
        spotLight.intensity = 0.5;

        var lightTarget = new THREE.Object3D();
        lightTarget.position.set(10,0,0);
        scene.add(lightTarget);

        spotLight.target = lightTarget;
        spotLight.castShadow = true;
        spotLight.shadowMapWidth = 1024;
        spotLight.shadowMapHeight = 1024;
        spotLight.shadowCameraNear = 0.1;
        spotLight.shadowCameraFar = 50;
        spotLight.shadowCameraFov = 160;
        spotLight.shadowCameraVisible = true;

        scene.add(spotLight);
    }

    // change material
    if (keyboard.pressed("M")) {
        var mat = new THREE.MeshPhongMaterial({ color: 0x00ff00 });
        mat.side = THREE.DoubleSide;
        plane.material = mat;
        }
}

1 个答案:

答案 0 :(得分:0)

以下是来自three.js编辑器的示例,该编辑器包含在库中。在运行时添加灯光时,将调用此函数:

function updateMaterials() {

    editor.scene.traverse( function ( node ) {

        if ( node.material ) {

            node.material.needsUpdate = true;

            if ( node.material instanceof THREE.MeshFaceMaterial ) {

                for ( var i = 0; i < node.material.materials.length; i ++ ) {

                    node.material.materials[ i ].needsUpdate = true;

                }

            }

        }

    } );

}

如您所见,它为场景中的所有其他素材设置needsUpdate标记。执行此操作时,应使用下一个渲染进行更新。你应该试一试。