# 114 Three.js实现深度遮挡的下雨特效

Three.js笔记 专栏收录该内容
118 篇文章 66 订阅

# 渲染深度图

        renderer.setRenderTarget(target);
depthScene.children = [terrain];
renderer.render(depthScene, orthCamera);
renderer.setRenderTarget(null);


# 实现下雨时的深度裁剪

        material.onBeforeCompile = function (shader, renderer) {
const getFoot = 
uniform float top;
uniform float bottom;
uniform float time;
uniform mat4 cameraMatrix;
varying float depth;
varying vec2 depthUv;
#include <common>
float angle(float x, float y){
return atan(y, x);
}
vec2 getFoot(vec2 camera,vec2 normal,vec2 pos){
vec2 position;

float distanceLen = distance(pos, normal);

float a = angle(camera.x - normal.x, camera.y - normal.y);

pos.x > normal.x ? a -= 0.785 : a += 0.785;

position.x = cos(a) * distanceLen;
position.y = sin(a) * distanceLen;

return position + normal;
}
;
const begin_vertex = 
vec2 foot = getFoot(vec2(cameraPosition.x, cameraPosition.z),  vec2(normal.x, normal.z), vec2(position.x, position.z));
float height = top - bottom;
float y = normal.y - bottom - height * time;
y = y + (y < 0.0 ? height : 0.0);
float ratio = (1.0 - y / height) * (1.0 - y / height);
depth = ratio;
y = height * (1.0 - ratio);
y += bottom;
y += position.y - normal.y;
vec3 transformed = vec3( foot.x, y, foot.y );
vec4 cameraDepth = cameraMatrix * vec4(transformed, 1.0);
;

const depth_vary = 
uniform sampler2D tDepth;
uniform float opacity;
varying float depth;
varying vec2 depthUv;

float decodeRGBA2Float(vec4 rgba)
{
return dot(rgba, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0));
}
;

const depth_frag = 
if(1.0 - depth < decodeRGBA2Float(texture2D( tDepth, depthUv ))) discard;
vec4 diffuseColor = vec4( diffuse, opacity );

"#include <common>",
getFoot
);
"#include <begin_vertex>",
begin_vertex
);

value: new THREE.Vector3(0, 200, 0)
}
value: 2000
}
value: -2000
}
value: 0
}
value: new THREE.Matrix4()
}
value: target.texture
}
};

• 3
点赞
• 1
评论
• 1
收藏
• 一键三连
• 扫一扫，分享海报

11-04

07-05
12-21
01-28
09-20 1万+
01-25 5866
02-01 3222