Three.js 学习记录shader黑客帝国数字雨

645 阅读2分钟

Three.js 学习记录shader黑客帝国数字雨

1691764893499.jpg

想锻炼锻炼自己输出能力
实现效果

QQ录屏20230811235241-00-00-00--00-00-03-1.gif

需要一定shader知识 使用glsl-canvas插件展示效果

分步骤实现

1、生成黑白渐变图

根据y轴高度生成渐变,y值越大越白

#ifdef GL_ES
precision mediump float;
#endif

uniform vec2 u_resolution;
uniform vec2 u_mouse;
uniform float u_time;

void main(){
    vec2 uv=gl_FragCoord.xy/u_resolution.xy;
    float col = uv.y;
    gl_FragColor = vec4(vec3(col), 1.0);
}

2、使用倒数

float col = .1/uv.y;

可以通过控制分子分母比值大小调整样式 比如

float col = .01/uv.y;

3、让图形动起来

在y轴上加上时间进行偏移

uv.y += u_time/2.;

QQ录屏20230811225651[00-00-00--00-00-02].gif

4、让光亮在x轴上变形

使用常用的三角函数sin

    uv.x *=5.;
    uv.y += sin(uv.x)+ u_time/2.;
    float col = .1/ fract(uv.y);

QQ录屏20230811230402[00-00-00--00-00-02].gif

提示:可以思考为什么是uv.x *5 不是uv *5

5、取整函数使用

波浪的效果还不能满足要求 为了实现平整的柱状效果使用floor floor shader自带的向下取整函数

  uv.y += sin(floor(uv.x))+ u_time/2.;

6、让每列下落的数组都不一致

对时间参数做修改,加入噪声与 x轴偏移量组成速度

float random(float val){
   return fract(sin(val*12.9898)*43758.545323);
}
    uv.x *=5.;
    uv.x = floor(uv.x);
    float speed  = cos(uv.x)*.2 +random(uv.x+2.1)*0.2+ 0.35; 
    uv.y += sin(floor(uv.x))+ u_time*speed ;
    float col = .1/ fract(uv.y);

7、开始数字部分

添加数字纹理,让图片随时间进行偏移

0123.png

    uv *=5.;
    uv=fract(uv);
    float offsetx=step(0.5,fract((u_time/2.)))/2.;
    float offsety=step(0.5,fract((u_time/3.)))/2.;
    vec4 color=texture2D(u_texture_0,vec2((uv.x+offsetx)/1.,uv.y+offsety));

QQ录屏20230811233955[00-00-00--00-00-03].gif

8、两个效果相乘再加上颜色加代码优化

(偷懒一下,有啥问题可以评论区见)

#ifdef GL_ES
precision mediump float;
#endif

uniform vec2 u_resolution;
uniform vec2 u_mouse;
uniform float u_time;
uniform sampler2D u_texture_0;

#define scale.8// 页面缩放比例
#define column 50.0// 列数

float random(float val){
  return fract(sin(val*12.9898)*43758.545323);
}

void main(){
  vec2 uv=gl_FragCoord.xy/u_resolution.xy;
  vec2 st=uv;
  st.x=(st.x)*column;
  st.x=floor(st.x);
  st=st*scale;
  float offset=sin(st.x*column);
  float speed=cos(st.x*column)*.15+random(st.x+2.1)*.2+.35;
  float y=(fract((st.y+u_time/3.*speed+offset)));
  uv*=column/2.;
  uv=fract(uv);
  float offsetx=step(.5,fract((u_time/2.)))/2.;
  float offsety=step(.5,fract((u_time/3.)))/2.;
  vec4 color=texture2D(u_texture_0,vec2((uv.x+offsetx)/1.,uv.y+offsety));
  color.xyz=color.xyz/(y*60.);
  color=color*vec4(.1,1.,.35,1.);
  gl_FragColor=color;
}

image.png

添加到threeJs中 (好像效果不是很好)

image.png

文章写的不多 欢迎大家多提点建议 886886