three.js源碼翻譯-SpotLightShadow.js
說明
SpotLightShadow類是聚光燈光的陰影,SpotLightShadow的創建可以在SpotLightShadow的源碼翻譯部分看到,總體來說就是創建了一個透視攝像機傳到LightShadow中去,默認參數投影出的效果差不多,但是同樣的要更加真實的話,還是要自己設置參數。
源碼位置及翻譯
源碼位置
src/light/SpotLightShadow.js
源碼翻譯
function SpotLightShadow() {
LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
}
SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
constructor: SpotLightShadow,
isSpotLightShadow: true,
//點光源和方向光源陰影不同有,點光源使用了透視攝像機,並且重寫了update方法
update: function ( light ) {
//只是對透視相機做的一般處理,因爲陰影的基類使用的是正交投影
var camera = this.camera;
var fov = _Math.RAD2DEG * 2 * light.angle;
var aspect = this.mapSize.width / this.mapSize.height;
var far = light.distance || camera.far;
if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
camera.fov = fov;
camera.aspect = aspect;
camera.far = far;
camera.updateProjectionMatrix();
}
}
} );
示例及案例
創建
let sphere = new THREE.SphereBufferGeometry(1, 16, 16);
let spotLight = new THREE.SpotLight(0xffff00, 2.0, 150);
spotLight.add(new THREE.Mesh(sphere, new THREE.MeshBasicMaterial({ color: 0xff00ff })));
spotLight.position.y = 100;
spotLight.castShadow = true;
spotLight.shadow.mapSize.width = 1024;
spotLight.shadow.mapSize.height = 1024;
spotLight.shadow.camera.near = 10;
spotLight.shadow.camera.far = 150;
spotLight.shadow.camera.fov = 45;
scene.add(spotLight);
spotLight.target = ground;
scene.add(spotLight.target);
注意的點
- spot光源爲啥有單獨的文件呢,就是因爲他的update方法和基類Shadow不一樣,所以重寫了一下。
- 需要將光源的.castShadow設置爲true,同時需要將接受陰影的mesh的.receiveShadow設置爲true,然後還有渲染器中的.shadowMap.enabled也要設置爲true。表格如下
操作物體/屬性 | 光源(eg:THREE.DirectionalLight) | 接受陰影的物體(THREE.Mesh) | 渲染器(THREE.WebGLRenderer) |
---|---|---|---|
.castShadow | ✅ Yes | ||
.receiveShadow | ✅ Yes | ||
.shadowMap.enabled | ✅ Yes |