Skip to content

组织你的场景

此笔记记录于DISCOVER three.js,大多数为其中的摘要,少数为笔者自己的理解

目录

meshGroup.js

js
import {
  SphereBufferGeometry,
  Group, 
  MathUtils,
  Mesh,
  MeshStandardMaterial,
} from 'three';

function createMeshGroup() {
  // a group holds other objects
  // but cannot be seen itself
  const group = new Group(); 

  const geometry = new SphereBufferGeometry(0.25, 16, 16); // 球

  const material = new MeshStandardMaterial({
    color: 'indigo',
  });

  const protoSphere = new Mesh(geometry, material);

  // add the protoSphere to the group
  group.add(protoSphere);

  // create twenty clones of the protoSphere
  // and add each to the group
  for (let i = 0; i < 1; i += 0.05) {
    const sphere = protoSphere.clone();

    // position the spheres on around a circle
    sphere.position.x = Math.cos(2 * Math.PI * i);
    sphere.position.y = Math.sin(2 * Math.PI * i);

    sphere.scale.multiplyScalar(0.01 + i);

    group.add(sphere); 
  }

  // every sphere inside the group will be scaled
  group.scale.multiplyScalar(2);

  const radiansPerSecond = MathUtils.degToRad(30);

  // each frame, rotate the entire group of spheres
  group.tick = (delta) => {
    group.rotation.z -= delta * radiansPerSecond;
  };

  return group;
}

export { createMeshGroup };

clone

  • three.js中几乎所有的对象都有一个.clone方法,它允许您创建该对象的相同副本。
  • clonedMesh也具有与mesh相同的几何体和材料。但是,几何体和材质不是克隆的,它们是共享的。如果我们对共享材质进行任何更改,例如,更改其颜色,所有克隆的网格将与原始网格一起更改。如果您对几何体进行任何更改,这同样适用。
  • 但是,您可以给一个克隆一个全新的材料,而原来的材料不会受到影响。
  • 自定义属性不会克隆,如.tick

组Group介绍

在 场景图中占据一个位置并且可以有子对象,但它们本身是不可见的。如果Scene代表整个宇宙,那么您可以将Group视为该宇宙中的单个 复合 对象。

每个场景对象都有继承自Object3D.add.remove的方法,就像GroupScene本身一样, 每个对象都可以在场景图中占据一个位置并拥有子对象。不同之处在于组是 纯粹的可组织对象。其他场景对象,如网格、灯光、相机等,除了在场景图中占据一席之地外,还有其他用途。但是,组的存在纯粹是为了帮助您操纵其他场景对象。