threejs使场景中物体有阴影

使场景中物体有阴影
1、对renderer设置

        this.renderer = new THREE.WebGLRenderer({ antialias: true });
        this.renderer.setPixelRatio(window.devicePixelRatio);
        this.renderer.setSize(window.innerWidth, window.innerHeight);
        this.renderer.shadowMap.enabled = true;
        this.renderer.shadowMap.type = THREE.PCFSoftShadowMap; //阴影类型
        this.renderer.gammaInput = true;
        this.renderer.gammaOutput = true;
        document.body.appendChild(this.renderer.domElement);

2、对mesh设置

  let mesh = new THREE.Mesh(new THREE.PlaneBufferGeometry(200, 200), new THREE.MeshPhongMaterial({
        color: 0x9cfcf99,
        depthWrite: false
    }));
    mesh.rotation.x = -Math.PI / 2;
    mesh.position.set(0, -20, 0)
    mesh.receiveShadow = true;
    this.scene.add(mesh);

3、对light设置。

    let light = new THREE.AmbientLight(0xffffff, 0.1);
    this.scene.add(light);

    let dirlight = new THREE.DirectionalLight(0xffffff);
    dirlight.position.set(-30, 120, -100);
    dirlight.castShadow = true;
    dirlight.shadowCameraVisible=true;
    dirlight.shadow.camera.top = 100;
    dirlight.shadow.camera.bottom = -100;
    dirlight.shadow.camera.left = -100;
    dirlight.shadow.camera.right = 100;
    dirlight.shadow.camera.near = 0.1;
    dirlight.shadow.camera.far = 500;
    this.scene.add(dirlight);

其他:
1、阴影类型:
THREE.BasicShadowMap = 0; //默认
THREE.PCFShadowMap = 1; //渐淡
THREE.PCFSoftShadowMap = 2; //渐淡柔化
2、mesh.castShadow = true; mesh.receiveShadow = true;
可以得出要使网格接受阴影,需要开启reciveShadow;要使网格在光照下产生阴影,需要开启castShadow
3、spotLight.shadowCameraVisible=true; shadowCameraVisible只有在老版本的threejs库中才支持,新版本已废除。
4、在创建 THREE.AmbientLight 时,颜色会应用到全局。该光源并没有特别的来源方向,并且 THREE.AmbientLight 不会产生阴影。
5、通常,不能将 THREE.AmbientLight 作为场景中唯一的光源,因为它会将场景中的所有物体渲染为相同的颜色,而不管是什么形状。在使用其他光源(如 THREE.SpotLight 或者 THREE.DirectionLight)的同时使用它,目的是弱化阴影或给场景添加一些额外的颜色。

你可能感兴趣的:(three.js学习)