111 three.js下雨进阶版,面只旋转y轴朝向相机

之前实现过,是利用的sprite永久朝向相机的特性实现的效果。但是这种效果对于雪还比较好,如果贴图修改成长条形的雨的话,从上往下看,就会有一种说不出的感觉,不真实。
案例查看地址:https://www.wjceo.com/blog/threejs2/2019-02-28/185.html
而我也通过修改shader和自己拼接渲染数据,实现了一个比较简单的渲染效果。接下来讲解一下实现逻辑:

第一步,创建一个包围盒,来设置范围

      const box = new THREE.Box3(
        new THREE.Vector3(-2000, -2000, -2000),
        new THREE.Vector3(2000, 2000, 2000)
      );

第二步,创建一个默认材质,并修改材质的shader

这里简单的提一句,three.js的材质对象是生成webgl的原生的program的工具,内置的那些材质都有相应的字符串拼接组成。
相应的,我们也可以通过拼接的方式,修改材质的默认着色器代码,从而达到自己的需求。

      material = new THREE.MeshBasicMaterial({
        transparent: true,
        opacity:.8,
        map: new THREE.TextureLoader().load("./color.png"),
        depthWrite: false,
      });

      material.onBeforeCompile = function (shader, renderer) {
        const getFoot = `
            uniform float top;
            uniform float bottom;
            uniform float time;
            #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);

                if(pos.x > normal.x){
                  a -= 0.785; 
                }
                else{
                  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;
            if(y < 0.0) y += height;
            float ratio = (1.0 - y /height) * (1.0 - y /height);
            y = height * (1.0 - ratio);
            y += bottom;
            y += position.y - normal.y;
            vec3 transformed = vec3( foot.x, y, foot.y );
            // vec3 transformed = vec3( position );
            `;
        shader.vertexShader = shader.vertexShader.replace(
          "#include <common>",
          getFoot
        );
        shader.vertexShader = shader.vertexShader.replace(
          "#include <begin_vertex>",
          begin_vertex
        );

        shader.uniforms.cameraPosition = {
          value: new THREE.Vector3(0, 200, 0),
        };
        shader.uniforms.top = {
          value: 2000,
        };
        shader.uniforms.bottom = {
          value: -2000,
        };
        shader.uniforms.time = {
          value: 0,
        };
        material.uniforms = shader.uniforms;
      };

第三步,通过包围盒生成相应的渲染数据

由于MeshBasicMaterial材质不受光照影响,所以,我们直接在拼接数据时, 将normal值设置面片的中心,一个正方形的面片需要由两个三角形组成,也就是最少四个顶点完成。
主要的操作就在这里,这里生成的数据,会在shader里面计算获取到y轴都为零情况下,沿中心点旋转的角度,通过此角度再生成一下旋转后,顶点需要渲染的位置。

      var geometry = new THREE.BufferGeometry();

      const vertices = [];
      const normals = [];
      const uvs = [];
      const indices = [];

      for (let i = 0; i < 1000; i++) {
        const pos = new THREE.Vector3();
        pos.x = Math.random() * (box.max.x - box.min.x) + box.min.x;
        pos.y = Math.random() * (box.max.y - box.min.y) + box.min.y;
        pos.z = Math.random() * (box.max.z - box.min.z) + box.min.z;

        const height = (box.max.y - box.min.y) / 15;
        const width = height / 50;

        vertices.push(
          pos.x + width,
          pos.y + height / 2,
          pos.z,
          pos.x - width,
          pos.y + height / 2,
          pos.z,
          pos.x - width,
          pos.y - height / 2,
          pos.z,
          pos.x + width,
          pos.y - height / 2,
          pos.z
        );

        normals.push(
          pos.x,
          pos.y,
          pos.z,
          pos.x,
          pos.y,
          pos.z,
          pos.x,
          pos.y,
          pos.z,
          pos.x,
          pos.y,
          pos.z
        );

        uvs.push(1, 1, 0, 1, 0, 0, 1, 0);

        indices.push(
          i * 4 + 0,
          i * 4 + 1,
          i * 4 + 2,
          i * 4 + 0,
          i * 4 + 2,
          i * 4 + 3
        );
      }

      geometry.addAttribute(
        "position",
        new THREE.BufferAttribute(new Float32Array(vertices), 3)
      );
      geometry.addAttribute(
        "normal",
        new THREE.BufferAttribute(new Float32Array(normals), 3)
      );
      geometry.addAttribute(
        "uv",
        new THREE.BufferAttribute(new Float32Array(uvs), 2)
      );
      geometry.setIndex(new THREE.BufferAttribute(new Uint32Array(indices), 1));

第四步,在帧更新内,更新材质的uniform

    var time = 0;
    function render() {
      time = (time + clock.getDelta() * 0.2) % 1;

      // console.log(time);

      material.cameraPosition = camera.position;

      if (material.uniforms) {
        material.uniforms.cameraPosition.value = camera.position;
        material.uniforms.time.value = time;
      }

      renderer.render(scene, camera);
    }

最后一步,就设置一个变量,然后通过帧更新,更新雨点的位置,直接在shader里面计算简单方便。

接下来付上demo源码:


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      html,
      body {
        margin: 0;
        padding: 0;
        height: 100%;
      }
    </style>
  </head>
  <body></body>
  <script src="../node_modules/three/build/three.js"></script>
  <script src="../node_modules/three/examples/js/controls/OrbitControls.js"></script>
  <script src="../node_modules/three/examples/js/libs/stats.min.js"></script>
  <script src="../node_modules/three/examples/js/libs/dat.gui.min.js"></script>
  <script>
    var camera, scene, renderer, stats, control, material;

    var sphere;

    var clock = new THREE.Clock();

    init();
    animate();

    function init() {
      camera = new THREE.PerspectiveCamera(
        40,
        window.innerWidth / window.innerHeight,
        1,
        15000
      );
      camera.position.z = 3000;

      scene = new THREE.Scene();
      scene.background = new THREE.Color(0x333333);
      
      const box = new THREE.Box3(
        new THREE.Vector3(-2000, -2000, -2000),
        new THREE.Vector3(2000, 2000, 2000)
      );

      material = new THREE.MeshBasicMaterial({
        transparent: true,
        opacity:.8,
        map: new THREE.TextureLoader().load("./color.png"),
        depthWrite: false,
      });

      material.onBeforeCompile = function (shader, renderer) {
        const getFoot = `
            uniform float top;
            uniform float bottom;
            uniform float time;
            #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);

                if(pos.x > normal.x){
                  a -= 0.785; 
                }
                else{
                  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;
            if(y < 0.0) y += height;
            float ratio = (1.0 - y /height) * (1.0 - y /height);
            y = height * (1.0 - ratio);
            y += bottom;
            y += position.y - normal.y;
            vec3 transformed = vec3( foot.x, y, foot.y );
            // vec3 transformed = vec3( position );
            `;
        shader.vertexShader = shader.vertexShader.replace(
          "#include <common>",
          getFoot
        );
        shader.vertexShader = shader.vertexShader.replace(
          "#include <begin_vertex>",
          begin_vertex
        );

        shader.uniforms.cameraPosition = {
          value: new THREE.Vector3(0, 200, 0),
        };
        shader.uniforms.top = {
          value: 2000,
        };
        shader.uniforms.bottom = {
          value: -2000,
        };
        shader.uniforms.time = {
          value: 0,
        };
        material.uniforms = shader.uniforms;
      };

      var geometry = new THREE.BufferGeometry();

      const vertices = [];
      const normals = [];
      const uvs = [];
      const indices = [];

      for (let i = 0; i < 1000; i++) {
        const pos = new THREE.Vector3();
        pos.x = Math.random() * (box.max.x - box.min.x) + box.min.x;
        pos.y = Math.random() * (box.max.y - box.min.y) + box.min.y;
        pos.z = Math.random() * (box.max.z - box.min.z) + box.min.z;

        const height = (box.max.y - box.min.y) / 15;
        const width = height / 50;

        vertices.push(
          pos.x + width,
          pos.y + height / 2,
          pos.z,
          pos.x - width,
          pos.y + height / 2,
          pos.z,
          pos.x - width,
          pos.y - height / 2,
          pos.z,
          pos.x + width,
          pos.y - height / 2,
          pos.z
        );

        normals.push(
          pos.x,
          pos.y,
          pos.z,
          pos.x,
          pos.y,
          pos.z,
          pos.x,
          pos.y,
          pos.z,
          pos.x,
          pos.y,
          pos.z
        );

        uvs.push(1, 1, 0, 1, 0, 0, 1, 0);

        indices.push(
          i * 4 + 0,
          i * 4 + 1,
          i * 4 + 2,
          i * 4 + 0,
          i * 4 + 2,
          i * 4 + 3
        );
      }

      geometry.addAttribute(
        "position",
        new THREE.BufferAttribute(new Float32Array(vertices), 3)
      );
      geometry.addAttribute(
        "normal",
        new THREE.BufferAttribute(new Float32Array(normals), 3)
      );
      geometry.addAttribute(
        "uv",
        new THREE.BufferAttribute(new Float32Array(uvs), 2)
      );
      geometry.setIndex(new THREE.BufferAttribute(new Uint32Array(indices), 1));

      scene.add(new THREE.Mesh(geometry, material));

      var axesHelper = new THREE.AxesHelper(500);
      scene.add(axesHelper);

      renderer = new THREE.WebGLRenderer({ antialias: true });
      renderer.setPixelRatio(window.devicePixelRatio);
      renderer.setSize(window.innerWidth, window.innerHeight);
      document.body.appendChild(renderer.domElement);

      stats = new Stats();
      document.body.appendChild(stats.dom);

      control = new THREE.OrbitControls(camera, renderer.domElement);

      window.addEventListener("resize", onWindowResize, false);
    }

    function onWindowResize() {
      windowHalfX = window.innerWidth / 2;
      windowHalfY = window.innerHeight / 2;

      camera.aspect = window.innerWidth / window.innerHeight;
      camera.updateProjectionMatrix();

      renderer.setSize(window.innerWidth, window.innerHeight);
    }

    //

    function animate() {
      requestAnimationFrame(animate);

      render();
      stats.update();
    }

    var time = 0;
    function render() {
      time = (time + clock.getDelta() * 0.2) % 1;

      // console.log(time);

      material.cameraPosition = camera.position;

      if (material.uniforms) {
        material.uniforms.cameraPosition.value = camera.position;
        material.uniforms.time.value = time;
      }

      renderer.render(scene, camera);
    }
  </script>
</html>

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
### 回答1: 要绕多个轴旋转,可以将多个旋转合并为一个四元数。假设要绕向量 $a$ 和向量 $b$ 旋转,可以先将它们规范化,然后计算出旋转角度 $\theta$,最后构造一个四元数来表示绕向量 $a$ 和向量 $b$ 的旋转: ```javascript var a = new THREE.Vector3(1, 0, 0).normalize(); var b = new THREE.Vector3(0, 1, 0).normalize(); var c = new THREE.Vector3().crossVectors(a, b).normalize(); var angle1 = Math.acos(a.dot(b)); var angle2 = Math.PI / 2 - angle1; var quaternion1 = new THREE.Quaternion().setFromAxisAngle(a, angle1); var quaternion2 = new THREE.Quaternion().setFromAxisAngle(c, angle2); var quaternion = new THREE.Quaternion().multiplyQuaternions(quaternion1, quaternion2); ``` 这段代码中,我们首先计算出向量 $a$ 和向量 $b$ 的叉积 $c$,这个向量就是旋转的轴,因为它垂直于向量 $a$ 和向量 $b$。然后,我们计算出旋转角度 $\theta$,这个角度可以通过向量 $a$ 和向量 $b$ 的点积来计算。接下来,我们构造两个四元数,分别表示绕向量 $a$ 和向量 $c$ 的旋转。最后,我们将这两个四元数相乘,得到的就是绕向量 $a$ 和向量 $b$ 的旋转四元数。 ### 回答2: three.js 的 quaternion 类提供了一个方便的方法来实现绕多个轴的旋转。一个 quaternion 是一种四元数,它可以用来表示空间中的旋转。 假设我们要旋转一个物体绕 X,Y 和 Z 轴旋转,我们可以创建三个 quaternion 对象分别表示这三个旋转。然后,我们可以通过将这三个旋转 quaternion 行乘法运算,得到一个新的 quaternion,此新 quaternion 表示了绕多个轴的旋转。 首先,我们需要创建三个旋转 quaternion 对象,分别表示绕 X、Y 和 Z 轴的旋转。可以使用 three.js 的 Quaternion 类的 setFromAxisAngle 方法来创建这些 quaternion。这个方法接受两个参数,第一个参数是表示旋转轴的三维向量,第二个参数是表示旋转角度的弧度值。 然后,我们需要将这三个旋转 quaternion 行乘法运算,以得到新的 quaternion,表示绕多个轴的旋转。可以使用 three.js 的 Quaternion 类的 multiplyQuaternions 方法来行 quaternion 的乘法。 最后,我们可以通过将这个新的 quaternion 赋值给物体的 quaternion 属性来实现绕多个轴旋转。 下面是一个实现绕多个轴旋转的例子: ``` // 创建旋转 quaternion 对象 var quaternionX = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(1, 0, 0), angleX); var quaternionY = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), angleY); var quaternionZ = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 0, 1), angleZ); // 将三个旋转 quaternion 行乘法运算 var rotationQuaternion = new THREE.Quaternion(); rotationQuaternion.multiplyQuaternions(rotationQuaternion, quaternionX); rotationQuaternion.multiplyQuaternions(rotationQuaternion, quaternionY); rotationQuaternion.multiplyQuaternions(rotationQuaternion, quaternionZ); // 将新的 quaternion 赋值给物体的 quaternion 属性 object.quaternion.copy(rotationQuaternion); ``` 通过这个例子,我们可以实现一个物体绕 X、Y 和 Z 轴的多轴旋转。 ### 回答3: three.js中的Quaternion是一种数学工具,可以用来旋转操作。通过使用Quaternion的四元数表示,我们可以绕多个轴旋转。 首先,我们需要创建一个Quaternion对象,并设置其初始值为单位四元数。可以使用以下代码来实现: ```javascript var quaternion = new THREE.Quaternion(); quaternion.set(0, 0, 0, 1); // 设置为单位四元数 ``` 接下来,我们可以使用quaternion对象的multiply方法来行连续旋转操作。假设我们想要绕X轴旋转θ度,Y轴旋转φ度,Z轴旋转ψ度,我们可以使用以下代码: ```javascript quaternion.multiply(new THREE.Quaternion().setFromEuler(new THREE.Euler( THREE.MathUtils.degToRad(θ), THREE.MathUtils.degToRad(φ), THREE.MathUtils.degToRad(ψ), 'XYZ' // 设置旋转顺序 ))); ``` 最后,我们可以将Quaternion对象应用到需要旋转的物体上,通过设置物体的rotation属性为quaternion对象,即可实现绕多个轴旋转。例如: ```javascript mesh.rotation.setFromQuaternion(quaternion); ``` 通过以上代码,我们就可以实现绕多个轴旋转的效果了。 需要注意的是,使用Quaternion旋转时,旋转顺序对最终结果有影响。在上面的代码中,我们使用了'XYZ'作为旋转顺序,你可以根据实际需要行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值