Search code examples
three.js

three js change the position of shadow camera of directlight


I have a huge plane that I'm using as a ground, i have a directionalLight as the sun light.

the problem is, this directionalLight can't cast shadow over all the plane, so I've decided to make the shadow camera of the directionalLight to follow the main PerspectiveCamera.

So, this my code:

camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
lightCameraConstant = 40;
dirLight = new THREE.DirectionalLight( 0xffffff, 1 );
dirLight.color.setHSL( 0.1, 0.5, 1 );
dirLight.position.set( 1500, 2000, 1500 );
dirLight.castShadow = true;

dirLight.shadow.mapSize.width = 4096;
dirLight.shadow.mapSize.height = 4096;

dirLight.shadow.camera.left = -lightCameraConstant;
dirLight.shadow.camera.right = lightCameraConstant;
dirLight.shadow.camera.top = lightCameraConstant;
dirLight.shadow.camera.bottom = -lightCameraConstant;
dirLight.shadow.camera.far = 3000;
dirLight.shadow.camera.near = 0.01;
dirLight.shadow.bias = -0.0001;
scene.add( dirLight );
var helper = new THREE.CameraHelper( dirLight.shadow.camera );
    scene.add( helper );

then in the animation function i use the following:

dirLight.shadow.camera.position.x = camera.position.x;
helper.update();

but this is not working, the shadow camera isn't changing its position at all.

1- how to change shadow camera position without changing the directionalLight position ?

2- is there any way to cover casting shadow over a big area without using insane resources ?


Solution

  • I couldn't change the position of shadow camera, but I found a work around.

    The workaround was, to change the whole directLight position and the target position with the main camera in a way that the angel between the target position and the directLight stay the same.

    I used this could:

    dirLight.position.x = camera.position.x - cameraStartPosition.x + 20 ;
    dirLight.position.z = camera.position.z - cameraStartPosition.z + 20;
    dirLight.target.position.set(( camera.position.x - cameraStartPosition.x),0,(camera.position.z - cameraStartPosition.z));
    

    cameraStartPosition is the start position of the camera, because my camera isn't starting at 0,0,0. and the rest of the fixed numbers are an offset that I want to keep between the main camera and the shadow camera.

    Hope this could help somebody.