我无法使用鼠标事件添加灯光 [英] I can't add light with mouse event

查看:28
本文介绍了我无法使用鼠标事件添加灯光的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我有以下功能

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

当我在我的 init 函数中使用它时它可以工作

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

有什么建议吗?

谢谢

推荐答案

您要在渲染至少一次后向场景添加灯光.

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

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

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;

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

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

three.js r.68

这篇关于我无法使用鼠标事件添加灯光的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆