I can't add light with mouse event

2019-01-29 08:32发布

问题:

I can't add light with keydown event in three.js scene.

I have the following function

function putLight(){
    light = new THREE.SpotLight( 0xffffff );
    light.position.set( 10, 80, 20 );
    light.target.position.set( 0, 0, 0 );

        light.castShadow = true;

        light.shadowCameraNear = 20;
        light.shadowCameraFar = 50;
        light.shadowCameraFov = 40;

        light.shadowMapBias = 0.1;
        light.shadowMapDarkness = 0.7;
        light.shadowMapWidth = 2*512;
        light.shadowMapHeight = 2*512;
    scene.add( light );
}

And it works when I use it in my init function

function init(){
    camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
    scene = new THREE.Scene();
geometry = new THREE.PlaneGeometry( 300, 300, 50, 50 );
    geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );

    material = new THREE.MeshLambertMaterial( { color: 0xdddddd } );

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

    mesh.position.copy(groundBody.position);
    mesh.castShadow = true;
    mesh.receiveShadow = true;
    scene.add( mesh );


    renderer = new THREE.WebGLRenderer();
    renderer.shadowMapEnabled = true;
    renderer.shadowMapSoft = true;
    renderer.setSize( window.innerWidth, window.innerHeight );

    document.body.appendChild(renderer.domElement);
}

it also works if I put it out of any function in main script:

initCannon();
init();
loadModel();
putLight();
render();

but it doesn`t work in the next situation

window.addEventListener("keydown",function(e){
    switch( e.keyCode ) {
        case 76:
            putLight();
            break;
    }
});

Any suggestions?

Thanks

回答1:

You are adding a light to the scene after rendering at least once.

As stated in the Wiki article How to Update Things with WebGLRenderer, properties that can't be easily changed in runtime (once a material is rendered at least once) include the number and types of lights.

If you must add the light after the first render, then you need to set

material.needsUpdate = true;

An alternate solution is to add the light prior to the first render, and set the light's intensity to zero.

three.js r.68