Three.js官網demo分析(三)--- 聚光燈與陰影

這是今天要分析的demo,這是源碼html

下面來分析幾段代碼git

1.控制器的設置github

// 初始化控制器
                var controls = new THREE.OrbitControls( camera, renderer.domElement );
                // 若是有animate函數,直接在函數裏用controls.update(), 不用下面的方式
                controls.addEventListener( 'change', render );
                // 最大最小移動距離
                controls.minDistance = 20;
                controls.maxDistance = 500;
                // 是否能夠平移
                controls.enablePan = true;
                // 平移速度
                controls.keyPanSpeed = 89;
                // 控制器聚焦的對象
                controls.target.copy( mesh.position );
                controls.update();

2.初始化聚光燈web

// 初始化聚光燈
                spotLight = new THREE.SpotLight( 0xffffff, 1 );
                // 聚光燈的位置
                spotLight.position.set( 50, 20, 0 );
                // 聚光燈光束的角度,設置的是角的一邊到角度二分線的角度
                spotLight.angle = Math.PI / 6;
                // 光束從中心到邊緣衰減的百分比,值爲從0到1的數字
                spotLight.penumbra = 0.5;
                // 沿着光照距離的衰減量, 但我改變數值沒什麼變化
                spotLight.decay = 20;
                // 從光源發出光的最大距離,其強度根據光源的距離線性衰減
                spotLight.distance = 200;

3.陰影的設置dom

// 是否投射陰影
                spotLight.castShadow = true;
                // 設置陰影的分辨率
                spotLight.shadow.mapSize.width = 1024;
                spotLight.shadow.mapSize.height = 1024;
                // 陰影能顯示的近點和遠點
                spotLight.shadow.camera.near = 10;
                spotLight.shadow.camera.far = 20;
                scene.add( spotLight );

4.輔助線的引入函數

// 模擬聚光燈的輔助線
                lightHelper = new THREE.SpotLightHelper( spotLight );
                scene.add( lightHelper );
                // 擬燈光相機的視椎體,傳入的參數至關於產生陰影的燈光相機
                shadowCameraHelper = new THREE.CameraHelper( spotLight.shadow.camera );
                scene.add( shadowCameraHelper );
                // 座標軸
                scene.add( new THREE.AxesHelper( 10 ) );

須要注意的是shadowCameraHelper = new THREE.CameraHelper( spotLight.shadow.camera )這句,生成視椎體以下webgl

clipboard.png

它模擬的是燈光相機的視椎體,並非咱們定義的相機的視椎體,傳入的參數是燈光相機,即spotLight.shadowspa

5.陰影的產生
首先要渲染器聲明使用陰影貼圖code

// 設置使用陰影貼圖  ??
                renderer.shadowMap.enabled = true;
                // 定義陰影貼圖類型  ?? 聽說這個類型的陰影看起來比較清晰
                renderer.shadowMap.type = THREE.PCFSoftShadowMap;

而後燈光設置htm

// 是否投射陰影
                spotLight.castShadow = true;
以後設置材質是否接受陰影
// 材質是否接受陰影
            mesh.receiveShadow = true;
最後設置材質是否投射陰影
// 對象是否被渲染到陰影貼圖中
            mesh.castShadow = true;
相關文章
相關標籤/搜索