上一节我们简单的说了一下THREE中必要的元素。今天我们深入探讨一下各种THREE的光源。

一 基础光源

基础光源有4种
1.THREE.AmbientLight(环境光源)
2.THREE.PointLight(点光源)
3.THREE.SpotLight(聚光灯)
4.THREE.DirectionalLight(平行光)

1.环境光源THREE.AmbientLight

环境光源没有特定的方向,他的颜色会应用到全局,它默认不会产生阴影。在没有光源的情况下,我们什么都看不到,而单独使用其他光源的情况下,没有照到的地方仍然是一片漆黑,所以环境光的存在会淡化这种现象。

单一的环境光一般不作为场景中的唯一光源。

2.点光源THREE.PointLight

点光源是一种单点发光,向各个方向照射的光源,因此考虑性能能问题,它默认不会产生阴影。与环境光不同它除了光源的颜色属性(color)外,还包括其他属性distance(光照的最大范围)、intensity(光强)、position(光源位置),下面是一个例子。

复制代码
var color = 0xccffcc; var pointLight = new THREE.PointLight(color); pointLight.distance = 100; pointLight.intensity = 1; scene.add(pointLight);
复制代码

渲染出来的结果为

点光源的应用场合主要是需要中心发光的物理,例如模拟太阳系中太阳的光源。

3.聚光灯THREE.SpotLight

聚光灯使用的范围非常广泛,它的光类似手电筒的光,用于高亮一些场景。而且它能够产生阴影。它的属性除了点光源的属性外还包括angle(角度范围)、castShadow(是否产生阴影)、exponent(光强递减度)。下面是代码。

复制代码
var color = 0xffffff; var spotLight = new THREE.SpotLight(color); spotLight.position.set(-40, 60, -10); spotLight.castShadow = true; spotLight.shadowCameraNear = 2; spotLight.shadowCameraFar = 200; spotLight.shadowCameraFov = 30; spotLight.target = plane; spotLight.distance = 0; spotLight.angle = 0.4;
复制代码

我们给聚光灯的castShadow属性设置了true。同事还需要指定谁产生阴影,谁来接受阴影。图中我们为正方体castShadow属性设置了true,为平面设置了receiveShadow属性设置了true。

4.平行光THREE.DirectionalLight

平行光就是光传递的方向相同的光,类似于太阳的光线,它的属性和聚光灯差不多(当然平行光没有角度属性,而是用shadowCameraNear、shadowCameraFar、shadowCameraLeft、shadowCameraRight、shadowCameraTop、shadowCameraBottom六个属性),代码如下。

复制代码
var color= 0xffaa00; var directionalLight = new THREE.DirectionalLight(color); directionalLight.position.set(0, 80, 0); directionalLight.castShadow = true; directionalLight.shadowCameraNear = 2; directionalLight.shadowCameraFar = 200; directionalLight.shadowCameraLeft = -50; directionalLight.shadowCameraRight = 50; directionalLight.shadowCameraTop = 50; directionalLight.shadowCameraBottom = -50; directionalLight.distance = 0; directionalLight.intensity = 0.5; directionalLight.shadowMapHeight = 1024; directionalLight.shadowMapWidth = 1024; directionalLight.target= cube; //注意target只能是一个Object3D()对象。
复制代码

directionalLight.shadowCamera的6个属性分别是平行光体的近面位置、远面位置、左面位置、右面位置、上面位置、下面位置,类似于正交投影相机的属性。

和spotLight一样,他们都有一个target属性,这个属性就是光照射的方向,同position属性一起确定了光源和照射的位置。这里我写了一个demo,不太清楚地同学可以看一下