简体   繁体   中英

Changing a three.js object's geometry

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.

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.

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. 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.

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

dispose() previous geometry object to prevent memory leaks.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM