Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object in loop won't cast shadow over whole lopop with Three.js

Why is not every cube in my loop casting a shadow?

I work with a directional light all of the cubes should cast shadows. But for some reason, it stops after 5 or so columns.

let dirLight = new THREE.DirectionalLight(0xFFFFFF, 1.5);
dirLight.position.set(300, -300, 400);
dirLight.castShadow = true;
scene.add(dirLight);

dirLight.shadow.mapSize.width = 512;
dirLight.shadow.mapSize.height = 512;
dirLight.shadow.camera.near = 0.5;
dirLight.shadow.camera.far = 1000;

let cubeGeometry = new THREE.BoxGeometry(1, 3, 1);
let cubeMaterial = new THREE.MeshLambertMaterial({
    color: 0xf54242
});

function drawCubes() {
    for (let c = 0; c < 25; c++) {
        for (let r = 0; r < 10; r++) {
            for (let t = 0; t < 2; t++) {
                let cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
                cube.position.x = c * 1.3;
                cube.position.y = r * 3.02;
                cube.position.z = t * 1.01;
                cube.castShadow = true;
                cube.receiveShadow = true;
                scene.add(cube);
            }
        }
    }

}
drawCubes();

enter image description here

like image 414
Marthy_Mc_Fly Avatar asked Oct 16 '22 10:10

Marthy_Mc_Fly


1 Answers

Your shadows are clipped since the default frustum of the directional shadow camera is too small. Try it like so:

const d = 50;

dirLight.shadow.camera.left = - d;
dirLight.shadow.camera.right = d;
dirLight.shadow.camera.top = d;
dirLight.shadow.camera.bottom = - d;

You can also use THREE.CameraHelper in order to debug the shadow camera. Very helpful for adjustments. Keep in mind that the shadow quality highly depends on the frustum. Tighter frustums produce sharper shadows.

scene.add( new THREE.CameraHelper( dirLight.shadow.camera ) );

three.js R109

like image 167
Mugen87 Avatar answered Oct 18 '22 23:10

Mugen87