threejs 绘制太阳系各星球后,我们每一个星球都是单独创建的网格模型,网格模型越多,对资源的消耗也越多,那么如何减少资源的消耗呢?
我们可以通过让多个星球共享同一个网格模型,来减少网格模型,从而减少资源消耗。
星球模型重构
星球模型每次创建都会初始化一个网格模型,为了减少资源消耗,我们只创建一个网格模型,然后通过模型的scale缩放来调整大小。
修改前
function addGeoMetry(textureImg, radius) {
var texLoader = new THREE.TextureLoader();
var texture = texLoader.load(link + textureImg)
var material = new THREE.MeshBasicMaterial({
map: texture,
}); //材质对象Material
var geometry = new THREE.SphereGeometry(radius, 25, 25);
var mesh = new THREE.Mesh(geometry, material); //网格模型对象Mesh
mesh.position.x = 0
return mesh
}
修改后
// 创建网格模型
var geometry = new THREE.SphereGeometry(1, 100, 100);
function addGeoMetry(geometry, textureImg, radius) {
var texLoader = new THREE.TextureLoader();
var texture = texLoader.load(link + textureImg)
var material = new THREE.MeshBasicMaterial({
map: texture,
}); //材质对象Material
var mesh = new THREE.Mesh(geometry, material); //网格模型对象Mesh
mesh.scale.set(radius, radius, radius)
return mesh
}
轨迹线调整
轨迹线每次绘制都会初始化一条轨迹线,我们调整一下,只初始化一次。
调整前
function circle(r) {
var arc = new THREE.ArcCurve(0, 0, r, 0, 2 * Math.PI, true);
// 获取点数越多,圆弧越光滑
var points = arc.getPoints(100); //返回一个vector2对象作为元素组成的数组
var geometry = new THREE.BufferGeometry();
//setFromPoints方法的本质:遍历points把vector2转变化vector3
geometry.setFromPoints(points);
var material = new THREE.LineBasicMaterial({
color: 0x0f4984,
linewidth: 1
});
// THREE.Line
var line = new THREE.LineLoop(geometry, material); //起始点闭合
// 圆弧线默认在XOY平面上,绕x轴旋转到XOZ平面上
line.rotateX(Math.PI / 2);
return line
}
调整后
// 创建轨道
var arc = new THREE.ArcCurve(0, 0, 1, 0, 2 * Math.PI, true);
// 获取点数越多,圆弧越光滑
var points = arc.getPoints(100); //返回一个vector2对象作为元素组成的数组
var lineGeometry = new THREE.BufferGeometry();
//setFromPoints方法的本质:遍历points把vector2转变化vector3
lineGeometry.setFromPoints(points);
var material = new THREE.LineBasicMaterial({
color: 0x0f4984
});
function circle(geometry, material, r) {
// THREE.Line
var line = new THREE.LineLoop(geometry, material); //起始点闭合
// 圆弧线默认在XOY平面上,绕x轴旋转到XOZ平面上
line.rotateX(Math.PI / 2);
line.scale.set(r, r, r);//通过line的scale属性设置公转轨迹半径
return line
}
效果演示
演示地址
threejs太阳系提高性能 共享Geometry Material
视频课程介绍
当前笔记是Three.js太阳系案例 threejs视频教程 绘制星体—Geometry、Material共享 学习实践笔记