【问题标题】:I can't add light with mouse event我无法通过鼠标事件添加灯光
【发布时间】:2014-10-24 03:44:10
【问题描述】:

我无法在 three.js 场景中使用 keydown 事件添加灯光。

我有以下功能

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 );
}

当我在我的初始化函数中使用它时它会起作用

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);
}

如果我把它放在主脚本中的任何函数之外,它也可以工作:

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

但是在接下来的情况下就不行了

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

有什么建议吗?

谢谢

【问题讨论】:

  • 你能加个小提琴吗?
  • 看看stackoverflow.com/questions/25497541/…对你有没有帮助。
  • 是的!成功了,非常感谢!
  • 为了清楚起见,我发布了一个答案,并提供了一个额外的解决方案。

标签: javascript 3d three.js


【解决方案1】:

至少渲染一次后,您正在向场景添加灯光。

如 Wiki 文章 How to Update Things with WebGLRenderer 中所述,在运行时(一旦材质至少渲染一次)无法轻易更改的属性包括灯光的数量和类型。

如果必须在第一次渲染后添加灯光,则需要设置

material.needsUpdate = true;

另一种解决方案是在第一次渲染之前添加灯光,并将灯光的intensity 设置为零。

three.js r.68

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-26
    • 2014-07-29
    • 2011-02-27
    • 2022-10-24
    • 2011-09-29
    相关资源
    最近更新 更多