学习[threejs] threejs 实现阴影效果

149 阅读1分钟

threejs 实现阴影效果

  1. 开启renderer的shadowMap的enable属性 // 默认是false

    renderer.shadowMap.enable=true
    
  2. 将能够产生阴影的光源设置castShadow属性为true

    light.castShadow = true
    
  3. 将能够接收投影的模型设置属性reciveShadow为true,表示能够呈现阴影效果

    mesh.reviveShadow = true
    

image.png

// 模型设置 reciveShadow属性 产生阴影
getBox() {
    const geometry = new THREE.PlaneGeometry(
        10,
        10,
        20,
        20
    );
    const material = new THREE.MeshPhongMaterial({});
    const mesh = new THREE.Mesh(geometry, material);
    mesh.rotateX(-Math.PI * 0.5);
    mesh.receiveShadow = true;
    return mesh;
}
getTestBox() {
    const geometry = new THREE.BoxGeometry(1, 1, 1);
    const material = new THREE.MeshPhongMaterial({});
    const mesh = new THREE.Mesh(geometry, material);
    mesh.position.setY(0.5);
    mesh.receiveShadow = true; // 模型本身产生阴影
    // mesh.castShadow = true; // 模型产生拖影效果
    return mesh;
}

image.png

// 被测模型设置castShadow属性,并且产生拖影效果
getBox() {
    const geometry = new THREE.PlaneGeometry(
        10,
        10,
        20,
        20
    );
    const material = new THREE.MeshPhongMaterial({});
    const mesh = new THREE.Mesh(geometry, material);
    mesh.rotateX(-Math.PI * 0.5);
    mesh.receiveShadow = true;
    return mesh;
}
getTestBox() {
    const geometry = new THREE.BoxGeometry(1, 1, 1);
    const material = new THREE.MeshPhongMaterial({});
    const mesh = new THREE.Mesh(geometry, material);
    mesh.position.setY(0.5);
    mesh.receiveShadow = true; // 模型本身产生阴影
    mesh.castShadow = true; // 模型产生拖影效果
    return mesh;
}

image.png

getSpotLight() {
    const light = new THREE.SpotLight(0xffc4c4, 1.1);
    light.position.set(0, 5, 5);
    light.castShadow = true;
    light.shadow.mapSize.width = 4096; // 调整光影贴图的大小,大小必须为2的幂次方,调整后会使得阴影更加精细
    light.shadow.mapSize.height = 4096; // 调整光影贴图的大小
    return light;
}
getSpotLight2() {
    const light = new THREE.SpotLight(0xc400c4, 1.1);
    light.position.set(0, 5, 5);
    light.castShadow = true;
    light.shadow.mapSize.width = 4096; // 调整光影贴图的大小,大小必须为2的幂次方,调整后会使得阴影更加精细
    light.shadow.mapSize.height = 4096; // 调整光影贴图的大小
    return light;
}
update() {
    this.pointLight.position.x =~
    Math.sin(this.times.elapsed * 0.0005) * 20;
    this.pointLight.position.z =
        Math.sin(this.times.elapsed * 0.0005) * 20;
    this.sportLight.position.x =
        Math.sin(this.times.elapsed * 0.0001) * 5;
    this.sportLight.position.y =
        Math.abs(
        Math.sin(this.times.elapsed * 0.0001)
    ) * 5;

    this.sportLight2.position.x =
        -Math.sin(this.times.elapsed * 0.0001) * 5;
    this.sportLight2.position.y =
        Math.abs(
        Math.sin(this.times.elapsed * 0.0001)
    ) * 5;
}