Three.js r124->r125, 一次从Geometry到BufferGeometry的迁移记录
nano71.com
2024/4/8 19:40:58
0 comments
69 views
前言
在Three.js r125版本更新中,Geometry和Face3将被永久删除,如果我从r124更新到此版本及以后的版本,这会直接导致我的网站主页项目中出现THREE.Geometry is not a constructor错误
尝试
我们可以从three.js仓库的deprecated文件夹获取已删除的功能,也可以直接迁移到性能更好的BufferGeometry,同时这也是官方推荐的,这里我选择后者
获取模型数据的不同
看一段我的项目获取Geometry.vertices数据的代码:
// 这段作用是用初始的随机粒子位置变化到模型的顶点位置数据中
for (let i = 0; i < geometry.vertices.length; i++) {
let tween = new Tween(geometry.vertices[i];);
const modelVertex = geographyList[index].vertices[i];
tween
.to({
x: modelVertex.x, y: modelVertex.y, z: modelVertex.z,
},)
.start()
}
模型顶点数据所对应的关系是:
geometry. vertices: Vector3[]
对应
bufferGeometry.attributes.position.array: any[]
则:
// Geometry用法
for (let i = 0; i < geometry.vertices.length; i++) {
const vertex = geometry.vertices[i];
const {x, y, z} = vertex;
}
// BufferGeometry用法
const positions = bufferGeometry.attributes.position.array;
for (let i = 0; i < positions.length; i += 3) {
const x = positions[i];
const y = positions[i + 1];
const z = positions[i + 2];
}
如果搭配Tween使用的话,还得加这一段:
tween.onUpdate((object) => {
positions[i] = object.x;
positions[i + 1] = object.y;
positions[i + 2] = object.z;
bufferGeometry.attributes.position.needsUpdate = true;
});
写入模型数据的不同
再看一段我的项目使用Geometry写入数据的代码:
// 这段是给每个粒子设置顶点位置信息和颜色
for (let i = 0; i < total; i++) {
const vertex = new Vector3();
vertex.x = rangeRandom(minZValue, -minZValue);
vertex.y = rangeRandom(minYValue, -minYValue);
vertex.z = rangeRandom(minZValue, -minZValue);
geometry.vertices.push(vertex);
geometry.colors.push(new Color(255, 255, 255));
}
模型顶点数据写入方法所对应的是:
geometry.vertices.push(Vector3)
geometry.colors.push(Color)
对应
bufferGeometry.setFromPoints(Vector3[])
bufferGeometry.setAttribute("color", Float32BufferAttribute)
则:
// BufferGeometry用法
const points = []
const colors = [];
for (let i = 0; i < total; i++) {
const vertex = new Vector3();
vertex.x = rangeRandom(minZValue, -minZValue);
vertex.y = rangeRandom(minYValue, -minYValue);
vertex.z = rangeRandom(minZValue, -minZValue);
points.push(vertex)
colors.push(255, 255, 255)
}
bufferGeometry.setFromPoints(points);
bufferGeometry.setAttribute("color", new Float32BufferAttribute(colors, 3));
最后
还有如果用到了THREE.JSONLoader,也会遇到THREE.Geometry is not a constructor错误,这可以直接使用我封装好的JSONLoader:
npm i @nano71/three-jsonloader
import JSONLoader from "@nano71/three-jsonloader";
nano71.com
2024/4/8 19:40:58
0 comments
69 views





