gpt4 book ai didi

Three.js 将 Material 数组分配给索引的 BufferGeometry

转载 作者:行者123 更新时间:2023-12-04 07:13:22 25 4
gpt4 key购买 nike

我有一个 BufferGeometry 三棱柱;我指定了 6 个顶点,然后添加索引以创建 8 个面(每个正方形平面 2 个三角形面)。
然后我设置了 5 个组,这样棱镜的每一侧都是一个组。
当我将单一 Material 分配给整个对象时,它可以在这里工作:https://jsfiddle.net/30ez17dw/1/
但是我希望能够分配一系列 Material ,以便每一侧( group )都有自己的 Material 。但是当我这样做时,对象消失了:
https://jsfiddle.net/30ez17dw/2/
如何修复我的代码以使 Material 数组起作用?

最佳答案

您没有正确指定您的组。像这样尝试:

var camera, scene, renderer;

init();
animate();

function init() {

camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.01, 10);
camera.position.z = 5;
camera.position.y = 2;
camera.lookAt(0, 0, 0);

scene = new THREE.Scene();


var geometry = new THREE.BufferGeometry();

const y = 0.866025404;
const y2 = 0.5;
const h = 1;

const vertices = new Float32Array([
-y2, 0, 0,
y2, 0, 0,
0, 0, y,

-y2, h, 0,
y2, h, 0,
0, h, y,
]);

const indices = [
0, 1, 2, // Top
5, 4, 3, // Bottom
3, 1, 0, // Back
1, 3, 4, // Back
0, 2, 3, // Left
5, 3, 2, // Left
4, 2, 1, // Right
2, 4, 5, // Right
];


geometry.setAttribute('position', new THREE.BufferAttribute(vertices, 3));
geometry.setIndex(indices);

geometry.computeVertexNormals();

geometry.clearGroups();
geometry.addGroup(0, 3, 0);
geometry.addGroup(3, 6, 1);
geometry.addGroup(6, 12, 2);
geometry.addGroup(12, 18, 3);
geometry.addGroup(18, 24, 4);

var material = [
new THREE.MeshBasicMaterial({
color: 0x00ff00
}),
new THREE.MeshBasicMaterial({
color: 0xff0000
}),
new THREE.MeshBasicMaterial({
color: 0x0000ff,
}),
new THREE.MeshBasicMaterial({
color: 0xffff00
}),
new THREE.MeshBasicMaterial({
color: 0x00ffff
})

];

var mesh = new THREE.Mesh(geometry, material); // , side: THREE.DoubleSide
scene.add(mesh);

renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild(renderer.domElement);

}

function animate() {

requestAnimationFrame(animate);
renderer.render(scene, camera);

}
body {
margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/three@0.132.0/build/three.min.js"></script>

您传递给 addGroup() 的索引是连续的。

关于Three.js 将 Material 数组分配给索引的 BufferGeometry,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68934851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com