携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第16天,点击查看活动详情 >>
在3D引擎里,雾通常是基于离摄像机的距离褪色至某种特定颜色的方式。在three.js中添加雾是通过创建
Fog或者FogExp2实例并设定scene的fog属性。
Fog让你设定near和far属性,代表距离摄像机的距离。任何物体比near近不会受到影响,任何物体比far远则完全是雾的颜色。在near和far中间的物体,会从它们自身材料的颜色褪色到雾的颜色。FogExp2会根据离摄像机的距离呈指数增长。
Fog接受三个参数,颜色,近点,原点
FogExp2接受两个参数,一个颜色,一个增长指数,它可以在相机附近提供清晰的视野,且距离相机越远,雾的浓度随着指数增长越快,是累进乘积的关系
创建fog的代码如下
const scene = new THREE.Scene();
{
const color = 0xFFFFFF; // white
const near = 10;
const far = 100;
scene.fog = new THREE.Fog(color, near, far);
}
创建FogExp2的代码如下
const scene = new THREE.Scene();
{
const color = 0xFFFFFF;
const density = 0.1;
scene.fog = new THREE.FogExp2(color, density);
}
density的默认值为0.00025
从下图可以看到,FogExp2 比较接近现实效果,但是 Fog 使用的更加普遍,因为它支持设定影响区域,所以你可以设定一定距离内显示清晰的场景,过了这段距离再褪色到某种颜色。
需要注意的是雾是作用在 渲染的物体 上的,是物体颜色中每个像素计算的一部分。这意味着如果你想让你的场景褪色到某种颜色,你需要设定雾 和 场景的背景颜色为同一种颜色。背景颜色通过scene.background属性设置。你可以通过 THREE.Color选择背景颜色设置,像下面这样:
scene.background = new THREE.Color('#F00'); // 红色
假如背景色和雾的颜色不一致会发生什么?看下图
接下来,我们同样通过lil-gui,添加helper来帮助我们理解雾的远近和颜色对渲染物体的影响,首先需要添加一个helper的类,来操控near和far
class FogGUIHelper {
constructor(fog) {
this.fog = fog;
}
get near() {
return this.fog.near;
}
set near(v) {
this.fog.near = v;
this.fog.far = Math.max(this.fog.far, v);
}
get far() {
return this.fog.far;
}
set far(v) {
this.fog.far = v;
this.fog.near = Math.min(this.fog.near, v);
}
}
const fogGUIHelper = new FogGUIHelper(scene.fog);
gui.add(fogGUIHelper, 'near', near, far).listen();
gui.add(fogGUIHelper, 'far', near, far).listen();
然后,假如我们还想改变颜色的话,需要在类的constructor函数内传入backgroundColor,所以constructor内需要添加以下代码
constructor(fog, backgroundColor) {
this.fog = fog;
this.backgroundColor = backgroundColor;
}
然后,还需要添加针对颜色处理的get和set
get color() {
return `#${this.fog.color.getHexString()}`;
}
set color(hexString) {
this.fog.color.set(hexString);
this.backgroundColor.set(hexString);
}
最后,依赖gui的addColor帮助我们改变颜色
const fogGUIHelper = new FogGUIHelper(scene.fog, scene.background);
gui.addColor(fogGUIHelper, 'color');
这样,我们就得到了一个可以操控远近和颜色的帮助界面,可以尝试调整near和far去理解雾的渲染原理和表现。