Three.js UV动画

Unity Shader 之 uv动画

最近有个需求是要在要web端实现一个火焰的效果,unity3d上有粒子系统很容易实现,three.js上就只能用uv动画来实现,网上搜了一下也没有找到现成可用的,于是就把unity3d中的shader用glsl翻译成webgl版本的,分享给有需要的小伙伴。

uv动画-火焰效果

关键代码:

    ...
    // 创建一个时钟对象
    let clock;
    let material;
    function init() {
      clock = new THREE.Clock();
      
      ...

      //加载uv贴图
      const texture = new THREE.TextureLoader().load('../textures/fire/fire8x4.png');

      //顶点着色器
      const VertexShader = `
          varying vec2 texcoord;
                void main()
          {            
              gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
              texcoord = uv;
          }
      `;

      //片元着色器
      const FragmentShader = `
          varying vec2 texcoord;
          uniform sampler2D _MainTex;
          uniform float _Time;
          uniform float _HorizontalAmount;
          uniform float _VerticalAmount;
          uniform float _Speed;
          void main()
          {
            float time = floor(_Time * _Speed);
            float row = floor(time / _HorizontalAmount);    // /运算获取当前行
            float column = time - row * _HorizontalAmount;  // %运算获取当前列
            
            //首先把原纹理坐标i.uv按行数和列数进行等分,然后使用当前的行列进行偏移
            vec2 uv = texcoord + vec2(column, -row);
            uv.x /= _HorizontalAmount;
            uv.y /= _VerticalAmount;

            uv.x = fract(uv.x);//取小数部分[0-1]
            uv.y = fract(uv.y);
            
            //纹理采样
            vec4 c = texture2D(_MainTex, uv);
            
            gl_FragColor = c;
          }
        `;

      // shader传值
      const uniforms = {
        _Time: { value: 0.0 },
        _MainTex: { value: texture },
        _Speed: { value: 20 },
        _HorizontalAmount: { value: 8 },
        _VerticalAmount: { value: 4 }
      }

      //创建材质球
      material = new THREE.ShaderMaterial({
        uniforms: uniforms,
        vertexShader: VertexShader,
        fragmentShader: FragmentShader,
        transparent: true//透明渲染
      });

      ...  
      
      // 创建一个片来显示uv动画
      const geom = new THREE.PlaneGeometry( 20, 20);
      const mesh = new THREE.Mesh(geom, material);
      mesh.rotation.x = -90;

      ...

      function animate() {
      var deltaTime = clock.getDelta();
      // 更新uniforms中时间,这样就可以更新着色器中time变量的值
      material.uniforms._Time.value += deltaTime;
  
      ...    

      }

源码地址
github:https://github.com/eangulee/three.js-study/blob/master/user/uvanimation.html

你可能感兴趣的:(Three.js UV动画)