threejs-geometry 是做什麼的?
Three.js 幾何體建立 - 內建形狀、BufferGeometry、自訂幾何體、實例化。用於建立 3D 形狀、處理頂點、建構自訂網格,或透過實例化渲染進行最佳化。
簡介
此技能提供使用 Three.js 建立幾何體的完整指南,涵蓋:
- 使用內建形狀(如立方體、球體、圓柱體等)
- 透過 BufferGeometry 建立自訂幾何體
- 手動定義頂點、法線與 UV 座標
- 使用 InstancedMesh 進行大量物件的實例化渲染
支援的平台
- 瀏覽器:透過 CDN 或打包工具(如 Webpack、Vite)使用 Three.js
- Node.js:使用
threenpm 套件
核心功能
1. 建立內建形狀
import { BoxGeometry, SphereGeometry, CylinderGeometry } from 'three';
const box = new BoxGeometry(1, 1, 1);
const sphere = new SphereGeometry(1, 32, 16);
const cylinder = new CylinderGeometry(1, 1, 2, 16);
2. 自訂 BufferGeometry
可透過頂點陣列建立自訂幾何體:
import { BufferGeometry, Float32BufferAttribute } from 'three';
const geometry = new BufferGeometry();
const vertices = [
-1.0, -1.0, 1.0,
1.0, -1.0, 1.0,
1.0, 1.0, 1.0,
];
geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
geometry.setIndex([0, 1, 2]);
3. 使用實例化渲染
適用於渲染大量相同幾何體:
import { InstancedMesh, Matrix4 } from 'three';
const mesh = new InstancedMesh(geometry, material, count);
const matrix = new Matrix4();
for (let i = 0; i < count; i++) {
matrix.setPosition(x, y, z);
mesh.setMatrixAt(i, matrix);
}
mesh.instanceMatrix.needsUpdate = true;
最佳實務
- 使用
BufferGeometry以獲得最佳效能 - 調整細分數(segments)以平衡品質與效能
- 對大量相同物件採用實例化渲染
- 幾何體使用後進行 dispose() 以釋放記憶體
環境變數
THREE_GEOMETRY_DEBUG:設定為true以啟用除錯輸出