THREE.JS-如何为我的 GLTF 模型添加阴影?

THREE.JS-How can I add shadows for my GLTF model?

我是 Three.js 的新手。我想知道如何让我的 GLTF 模型对自己投下阴影?我一直在尝试不同的事情,但是我不确定我是否做对了。光源是 PointLight,相机是 Perspective IDK 如果重要请告诉我。 这是代码。 请谢谢 :)


var scene = new THREE.Scene();
    var camera = new THREE.PerspectiveCamera(
        60,
        window.innerWidth / window.innerHeight,
        0.01,
        1000
    );
    //camera.rotation.x=-20*Math.PI/180;
    var renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.shadowMap.enabled = true;
    document.body.appendChild(renderer.domElement);


    window.addEventListener('resize', () => {
        renderer.setSize(window.innerWidth, window.innerHeight);
        camera.aspect = window.innerWidth/ window.innerHeight;
        
        
        camera.updateProjectMatrix();
    });


    function mousemovement(event) {
        const mouseX = (event.clientX / window.innerWidth) * 2 - 1;
        const mouseY = -(event.clientY / window.innerHeight) * 2 + 1;
  
        light.position.x = mouseX * 11 + 2 ;

       light.position.y = mouseY * 4 + 4.5 ;
    };

    var numberofclicks = 2;

    window.addEventListener('mousemove', mousemovement);
    
    window.addEventListener('click', e =>{
        numberofclicks = numberofclicks + 1;
        if(numberofclicks % 2 == 0) {
    window.addEventListener('mousemove', mousemovement);
    }
    else {
    window.removeEventListener('mousemove', mousemovement);
    }
    });

    

    //GLTF moldal
    var loader = new GLTFLoader();

     loader.load("wrktblv2.gltf", function (gltf) {

            loader.castShadow = true;
            loader.receiveShadow = true;
         scene.add(gltf.scene);

     });
     
     var light = new THREE.PointLight(0xffffff, 2, 20);
     
     light.position.set(1,10,2)
    
     scene.add(light);
     
     camera.position.set(2,3,9);

     
     
        //const lightHelper = new THREE.PointLightHelper(light);
        //const gridHelper = new THREE.GridHelper(200,50);
        //scene.add(lightHelper, gridHelper);
     
    function animate(){
         requestAnimationFrame(animate);
         renderer.render(scene,camera);      
     }
     animate();

再次感谢,干杯!


编辑--我得到了一些关于阴影的帮助,但现在有一个问题。


The issue.

尝试添加 light.castShadow = true。 此外,您不应在加载器上投射阴影,而应在每个网格上投射阴影。所以替换

loader.castShadow = true;
loader.receiveShadow = true;

gltf.scene.traverse(function(child) {
    if (child.isMesh) {
      child.castShadow = true;
      child.receiveShadow = true;
    }
})