【bug优化】Three.js 中实现圆角立方体的详尽指南
// 引入Three.js
import * as THREE from 'three';
// 创建场景
const scene = new THREE.Scene();
// 创建相机
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
// 创建渲染器
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 创建圆角立方体
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshLambertMaterial({ color: 0xff0000 });
geometry.faces.forEach(face => {
// 设置面的圆角半径
const radius = 0.1;
for (let i = 0; i < face.vertexCount; i++) {
const vertex = geometry.vertices[face.a + i];
vertex.x = vertex.x > 0 ? vertex.x - radius : vertex.x + radius;
vertex.y = vertex.y > 0 ? vertex.y - radius : vertex.y + radius;
vertex.z = vertex.z > 0 ? vertex.z - radius : vertex.z + radius;
}
});
geometry.computeFaceNormals(); // 计算面法线
geometry.verticesNeedUpdate = true; // 标记顶点需要更新
geometry.normalsNeedUpdate = true; // 标记法线需要更新
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
这段代码创建了一个具有圆角的立方体,并且在Three.js场景中渲染了它。通过修正原始代码中的错误,确保了面法线的正确计算,以及更新了顶点和法线缓存,使得圆角效果能够正常显示。
评论已关闭