之前用这种方式创建Line和在render中更新line两点位置:
function createLinkLine(parent, son) {
let points = [parent.position, son.position];
let geometry = new THREE.BufferGeometry();
geometry.setFromPoints(points);
let line = new THREE.Line(geometry, g_linkLineMaterial);
line.wxhParent = parent;
line.wxhSon = son;
g_scene.add(line);
return line;
}
for (let i = 0; i < g_lines.length; i++) {
let points = [g_lines[i].wxhParent.position, g_lines[i].wxhSon.position];
//如果不dipose后重建,微信中gc会来不及回收一直涨
//加了dispose后,抖音里面内存一直涨
let geometry=g_lines[i].geometry;
geometry.dispose();
geometry = new THREE.BufferGeometry();
geometry.setFromPoints(points);
g_lines[i].geometry = geometry;
}
在微信小程序中没有问题,但是发现在抖音小游戏中会有内存泄露,不是GC来不及回收,内存一直涨。
google找到解法:
javascript - Drawing a line with three.js dynamically - Stack Overflow
function createLinkLine(parent, son) {
let positions = new Float32Array(2 * 3);
positions[0]=parent.position.x;
positions[1]=parent.position.y;
positions[2]=parent.position.z;
positions[3]=son.position.x;
positions[4]=son.position.y;
positions[5]=son.position.z;
let geometry = new THREE.BufferGeometry();
geometry.setAttribute('position',new THREE.BufferAttribute(positions,3));
let line = new THREE.Line(geometry, g_linkLineMaterial);
line.wxhParent = parent;
line.wxhSon = son;
g_scene.add(line);
return line;
}
for (let i = 0; i < g_lines.length; i++) {
//这个方法没有内存泄露
let points=g_lines[i].geometry.attributes.position.array;
points[0]=g_lines[i].wxhParent.position.x;
points[1]=g_lines[i].wxhParent.position.y;
points[2]=g_lines[i].wxhParent.position.z;
points[3]=g_lines[i].wxhSon.position.x;
points[4]=g_lines[i].wxhSon.position.y;
points[5]=g_lines[i].wxhSon.position.z;
g_lines[i].geometry.attributes.position.needsUpdate = true;
}