跳到主要内容
← Noise

Noise

Random Ranges

shader-learning 自学第 2 课:Random Ranges

实时渲染 · 2D 片段 GLSL

第 2 课:Random Ranges

实现

uniform vec2 iResolution;
uniform float iTime;

// returns: [0.0, 1.0];
float random(float x) {
   float r = fract(sin(x * 12.34) * 1234.5678);
   return r;
}

void main() {
  vec2 ratio = vec2(iResolution.x / iResolution.y, 1.0);
  vec2 uv = gl_FragCoord.xy / iResolution.xy;
  uv *= ratio;

  float time = iTime * 0.75;
  int particlesCount = 10;
  float spawnDelta = 1.0 / float(particlesCount);
  float size0 = 0.4;
  float size1 = 0.0;
  vec2 dir0 = vec2(0.3, 1.0);
  vec2 dir1 = vec2(-0.3, 1.0);
  vec3 color0 = vec3(1.0, 0.5, 0.0);
  vec3 color1 = vec3(1.0, 0.0, 0.0);

  vec3 result = vec3(0.0);
  for (int i = 0; i < particlesCount; i++) {
    float progress = fract(time + float(i) * spawnDelta);
    vec2 dir = mix(dir0, dir1, random(float(i)));

    // change position
    vec2 pos = vec2(0.5, 0.1) * ratio + dir * progress;

    float size  = mix(size0, size1, progress);
    vec3  color = mix(color0, color1, progress);

    float t = 1.0 - smoothstep(0.0, size, distance(uv, pos));
    result += color * t;
  }

  gl_FragColor = vec4(result, 1.0);
}