【threejs效果】圆形轨道

已被阅读 1736 次 | 文章分类:javascript | 2021-12-01 23:15

使用threejs THREE.CircleGeometry方法创建四种不同颜色不同半径和转速的轨道圆

1 原理

创建一个圆形mesh,然后动态旋转即可,用到的api如下;可以去threejs官方api查看具体用法和参数定义

(1) THREE.CircleGeometry:创建圆形面

(2) THREE.EdgesGeometry:获取圆形面的轮廓

(3) new THREE.LineDashedMaterial:创建虚线材质

(4) new THREE.LineSegments:创建线mesh;注意创建虚线材质必须 line.computeLineDistances();否则不生效

2 效果

如下创建四种不同半径,不同颜色,不同转速的圆形轨道

/net/upload/image/20211201/9c9ac85c-f723-4a03-b68c-970921884bdd.gif

3 代码

                                            
  // 轨道参数
  const orbitParams=[{
    radius:50,
    color:"red",
    speed:3,
    dashSize:3
  },{
    radius:100,
    color:"green",
    speed:-3,
    dashSize:5
  },{
    radius:150,
    color:"yellow",
    speed:10,
    dashSize:10
  },{
    radius:250,
    color:"pink",
    speed:-2,
    dashSize:30
  }]
  // 轨道组合
  let orbit=new Group();
  orbit.name="orbit"
  orbitParams.forEach((item)=>{
    // 几何体
    let geometry = new THREE.CircleGeometry(item.radius, 150);
    // 轮廓
    const edges = new THREE.EdgesGeometry( geometry );
    // 材质
    const material = new THREE.LineDashedMaterial( {
      color: item.color,
      linewidth: 2,
      scale: 1,
      dashSize: item.dashSize,
      gapSize: 10,
    } );
    // mesh
    const line = new THREE.LineSegments( edges, material );
    line.speed=item.speed
    line.rotateX(-Math.PI/2);
    line.computeLineDistances();
    orbit.add(line);
  })
  scene.add(orbit)
                                            
                                        
                                            
animate();
function animate() {
  let step = 0.002;
  let orbit = scene.getObjectByName("orbit");
  if (orbit) {
      orbit.traverse((item) => {
          if (item.speed) {
            item.rotation.z += step * item.speed;
          }
      });
  }
  requestAnimationFrame(animate);
  controls.update();
  renderer.render(scene, camera);
}
                                            
                                        

4 旋转方式

上面再animate函数中,对mesh进行旋转操作,如下是另一种方式,也可以实现同等效果

                                            
    updateZ();
    function updateZ(){ 
      if (orbit) {
          orbit.traverse((item) => {
              if (item.speed) {
                item.rotateZ(Math.PI/(item.speed*100));
              }
          });
      }
      requestAnimationFrame(updateZ)
    }
                                            
                                        

QQ:3410192267 | 技术支持 微信:popstarqqsmall

Copyright ©2017 xiaobaigis.com . 版权所有 鲁ICP备17027716号