Three.js 125版本后基于BufferGeometry制作切面球体的代码改造方案问询
Great question—since Three.js retired the old Geometry class in v125 and moved exclusively to BufferGeometry, we need to adjust how we manipulate vertex data (since BufferGeometry uses typed arrays instead of mutable vertex objects). Here's how to replicate your sliced sphere effect in modern versions:
Step 1: Create a Subdivided Box Buffer Geometry
Instead of BoxGeometry, use BoxBufferGeometry (the modern, performant equivalent). We’ll still use high subdivision counts to get the smooth sphere shape later:
const radius = 1; // Adjust this to your desired sphere size const geometry = new THREE.BoxBufferGeometry(1, 1, 1, 64, 64, 64);
Step 2: Normalize and Scale Vertices
With BufferGeometry, vertex positions are stored in a typed array under geometry.attributes.position. We need to access this array, process each (x,y,z) triplet, normalize it, then scale by your radius:
// Get the raw position data as a Float32Array const positions = geometry.attributes.position.array; // Loop through each vertex (3 values per vertex: x, y, z) for (let i = 0; i < positions.length; i += 3) { const x = positions[i]; const y = positions[i + 1]; const z = positions[i + 2]; // Calculate the length of the vertex vector const length = Math.sqrt(x * x + y * y + z * z); // Normalize and scale by radius positions[i] = (x / length) * radius; positions[i + 1] = (y / length) * radius; positions[i + 2] = (z / length) * radius; } // Mark the position attribute as updated so Three.js knows to refresh it geometry.attributes.position.needsUpdate = true;
Step 3: Post-Processing (Normals, Bounds, etc.)
Most of the post-processing methods you used still exist for BufferGeometry, though some manual update flags are no longer needed (since we already marked the position attribute as updated). Here’s the adjusted version:
geometry.computeVertexNormals(); geometry.computeFaceNormals(); geometry.computeBoundingSphere(); geometry.computeBoundingBox(); // If you're using morph targets, keep this line (otherwise you can omit it) // geometry.computeMorphNormals();
Key Differences from the Old Code
- We no longer iterate over
verticesobjects—instead, we work directly with the typed array inattributes.position. - Only the modified attribute (
position) needs itsneedsUpdateflag set; old flags likeverticesNeedUpdateorelementsNeedUpdatedon’t exist inBufferGeometry. BoxBufferGeometryis a drop-in replacement forBoxGeometry(all constructor parameters are identical).
This will give you the exact same sliced sphere effect as your old code, but optimized for modern Three.js versions!
内容的提问来源于stack exchange,提问作者user824624

