简体   繁体   中英

Javascript Three.JS Shadow Maps Not Working

I'm kinda new to Three.js, I'm enjoying it a whole bunch, though I'm having an issue with shadow maps, I've read and looked everywhere but I just can't get it to work, can somebody point me in the direction of what I'm doing wrong?

    var scene = new THREE.Scene();
    var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
    var renderer = new THREE.WebGLRenderer();

    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);

    var geometry = new THREE.BoxGeometry(1,1,1);
    var cube = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial( {color: 0x808080 } ));
    cube.castShadow = true;
    scene.add( cube );

    camera.position.y = 2;

    var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
    directionalLight.position.set( 0, 10, 0 );
    directionalLight.castShadow = true;
    scene.add( directionalLight );

    var geo2 = new THREE.BoxGeometry(5,0.1,5);

    var floor = new THREE.Mesh(geo2, new THREE.MeshLambertMaterial( {color: 0x808080 } ));
    floor.position.y = -1;
    floor.receiveShadow = true;
    scene.add(floor);

    renderer.shadowMapEnabled = true;
    renderer.shadowMapType = THREE.PCFSoftShadowMap;


    var ambient = new THREE.AmbientLight( 0x111111 );
    directionalLight.shadowCameraVisible = true;
    scene.add( ambient );


    renderer.shadowCameraNear = 3;
    renderer.shadowCameraFar = camera.far;
    renderer.shadowCameraFov = 50;

    function animate() {
        camera.lookAt({x:0,y:0,z:0});
        var timer = Date.now() * 0.0002;
        camera.position.x = Math.cos(timer) * 5;
        camera.position.z = Math.sin(timer) * 5;
        requestAnimationFrame(animate);
        render();
    }

    function render() {
        cube.rotation.x += 0.1;
        cube.rotation.y += 0.1;

        renderer.render(scene, camera);
    }
    animate();

These three lines:

renderer.shadowCameraNear = 3;
renderer.shadowCameraFar = camera.far;
renderer.shadowCameraFov = 50;

should be on your light not the renderer; so

directionalLight.shadowCameraNear = 3;
directionalLight.shadowCameraFar = camera.far;
directionalLight.shadowCameraFov = 50;

and since your light is directional you will need:

directionalLight.shadowCameraLeft = -500;
directionalLight.shadowCameraRight = 500;
directionalLight.shadowCameraTop = 500;
directionalLight.shadowCameraBottom = -500;

and you might need to play around with these values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM