如何在 Three.js 立方体中使用多种材质? [英] How to use multiple materials in a Three.js cube?
问题描述
我正在尝试使用 Three.js 来渲染一个带有 6 个不同图像的立方体.
I am trying to use Three.js to render a cube with 6 different images on the faces.
THREE.CubeGeometry 的构造函数如下所示:
The constructor of THREE.CubeGeometry looks like this:
THREE.CubeGeometry = function ( width, height, depth, segmentsWidth, segmentsHeight, segmentsDepth, materials, sides )
从代码中可以看出,materials"应该是一个材质,或者是6种不同材质的数组,但是这里传入的材质好像从来没有在渲染时使用过.
I can see from the code that "materials" is expected to be either a material, or an array of 6 different materials, but the materials passed in here never seem to be used when rendering.
相反,给 Mesh 构造函数的单一材质用于所有 6 个面.
Instead, the single material given to the Mesh constructor is used for all 6 faces.
var face_materials = ... <load 6 textures here>...
var cube_g = new THREE.CubeGeometry(400,400,400,1,1,1, face_materials); // <= ignored?
var cube = new THREE.Mesh(cube_g, some_material); // <= this is used instead
即使我将 null 或 undefined 作为some_material"传递,它似乎也覆盖了 face_material 并且什么都不渲染.
Even if I pass null or undefined as the "some_material", it seems to override the face_materials and render nothing.
有没有办法使用 CubeGeometry 来完成这项工作?还是我必须分别创建 6 个面并将它们添加到场景中?
Is there a way to make this work using CubeGeometry? Or do I have to create the 6 faces separately and add them to the scene?
推荐答案
您需要为网格使用 THREE.MeshFaceMaterial.示例代码如下:
You need to use THREE.MeshFaceMaterial for the mesh. Here's example code:
var materials = [];
for (var i=0; i<6; i++) {
var img = new Image();
img.src = i + '.png';
var tex = new THREE.Texture(img);
img.tex = tex;
img.onload = function() {
this.tex.needsUpdate = true;
};
var mat = new THREE.MeshBasicMaterial({color: 0xffffff, map: tex});
materials.push(mat);
}
var cubeGeo = new THREE.CubeGeometry(400,400,400,1,1,1, materials);
var cube = new THREE.Mesh(cubeGeo, new THREE.MeshFaceMaterial());
这篇关于如何在 Three.js 立方体中使用多种材质?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!