[英]Changing a three.js object's geometry
I am trying to change the geometry of some objects in a three.js scene. 我正在尝试更改Three.js场景中某些对象的几何形状。 I have an almost-working piece of code where a mouse click triggers the change, but got the following problem: the (rendered) shape is only changed on the first mouse click, even though the geometry is also successfully modified by each following clicks.
我有一段几乎可以正常工作的代码,其中单击鼠标会触发更改,但是出现了以下问题:(渲染的)形状仅在第一次单击鼠标时更改,即使随后的每次单击也成功修改了几何形状。 Using v66 or v68 of three.js library, if it is relevant.
如果相关,请使用three.js库的v66或v68。
I read Three.js: Completely change object's Geometry and Updating a geometry inside a mesh does nothing but couldn't get my code to work so far. 我读了Three.js:完全更改对象的Geometry和更新网格中的几何没有任何作用,但是到目前为止无法使我的代码正常工作。
Relevant parts of my code: 我的代码的相关部分:
var count = 0, item, geometry;
var geoms = [new THREE.SphereGeometry(2), new THREE.BoxGeometry(3, 3, 3)];
function init() {
geometry = geoms[count];
item = new THREE.Mesh(geometry, material);
scene.add(item);
}
// Mouse click listener.
function handleClick(event) {
count = 1 - count;
geometry = geoms[count];
item.geometry = geometry;
/* With that next line, on the first click, the sphere
* becomes a cube (as intended), but further clicks don't
* change the view anymore, even though item.geometry is
* modified.
*/
item.geometry.buffersNeedUpdate = true;
/* If I try next line instead, I got the following error:
* "TypeError: l.geometryGroupsList is undefined"
* from three.js.
*/
// item.geometry.verticesNeedUpdate = true;
}
Here is a jsfiddle of a (non-)working example. 这是一个(非工作示例)的jsfiddle。 There is a sphere on screen, a click will make it a cube.
屏幕上有一个球体,单击将使其变成立方体。 Further clicks are supposed to switch between sphere and cube, but nothing change on-screen.
应该进一步单击以在球体和立方体之间切换,但屏幕上没有任何变化。
I don't know exactly why this happens. 我不知道为什么会这样。 It is unable to update geometry of mesh by a geometry object once used.
一旦使用几何对象,就无法更新网格的几何。
.clone()
works in this case. .clone()
在这种情况下有效。
item.geometry.dispose();
item.geometry = geometry.clone();
dispose()
previous geometry object to prevent memory leaks. dispose()
先前的几何对象以防止内存泄漏。
There would be a better solution. 会有更好的解决方案。
i found this code to run the fastest: 我发现这段代码运行最快:
item.geometry.computeFaceNormals();
item.geometry.computeVertexNormals();
item.geometry.normalsNeedUpdate = true;
item.geometry.verticesNeedUpdate = true;
item.geometry.dynamic = true;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.