更改 Three.js 对象的几何形状 [英] Changing a three.js object's geometry

查看:48
本文介绍了更改 Three.js 对象的几何形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更改three.js 场景中某些对象的几何形状.我有一段几乎可以工作的代码,其中单击鼠标会触发更改,但遇到以下问题:(渲染的)形状仅在 第一次 鼠标单击时才更改,即使几何图形也是每次点击都成功修改.使用three.js 库的v66 或v68(如果相关).

I am trying to change the geometry of some objects in a three.js scene. 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:完全改变对象的几何形状更新网格内的几何体没有任何作用,但到目前为止无法使我的代码正常工作.

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.

我的代码的相关部分:

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;
}

这里是一个(非)工作示例的 jsfiddle.屏幕上有一个球体,点击一下就会变成一个立方体.进一步点击应该会在球体和立方体之间切换,但屏幕上没有任何变化.

Here is a jsfiddle of a (non-)working example. 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() 在这种情况下有效.

item.geometry.dispose();
item.geometry = geometry.clone();

dispose() 之前的几何对象以防止内存泄漏.

dispose() previous geometry object to prevent memory leaks.

会有更好的解决方案.

这篇关于更改 Three.js 对象的几何形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆