使用Three.js在立方体的六个面上应用不同的纹理。

35

我正在尝试创建一个使用不同纹理的三维立方体(类似于骰子)。

这是在我的沙盒环境中,应该会生成一个旋转的立方体,每个面都有骰子图像(1-6)。完成后,我打算将其用于基于浏览器的游戏。我已经在Chrome中测试了这个示例,但考虑为了获得更多的浏览器支持而将其更改为canvas渲染器。

我在SO上看了几个问题以及其他大量谷歌搜索,尽管我认为自己已经找到了答案(实际上似乎相当简单),但我就是无法让它工作。

我对three.js还比较新,但对JavaScript很熟悉。

我参考的页面有:

SO - three.js cube with different texture on each face

SO - three.js cube with different texture faces

evanz - Test three.js cube

以及enriquemorenotent.com - three.js building a cube with different materials on each face

我的代码:

var camera, scene, renderer, dice;

init();
animate();

function init() {
    renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);

    scene = new THREE.Scene();

    camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 1000);
    camera.position.set(110, 110, 250);
    camera.lookAt(scene.position);
    scene.add(camera);


    var materials = [
       new THREE.MeshLambertMaterial({
           map: THREE.ImageUtils.loadTexture('/Content/Images/dice-1-hi.png')
       }),
       new THREE.MeshLambertMaterial({
           map: THREE.ImageUtils.loadTexture('/Content/Images/dice-2-hi.png')
       }),
       new THREE.MeshLambertMaterial({
           map: THREE.ImageUtils.loadTexture('/Content/Images/dice-3-hi.png')
       }),
       new THREE.MeshLambertMaterial({
           map: THREE.ImageUtils.loadTexture('/Content/Images/dice-4-hi.png')
       }),
       new THREE.MeshLambertMaterial({
           map: THREE.ImageUtils.loadTexture('/Content/Images/dice-5-hi.png')
       }),
       new THREE.MeshLambertMaterial({
           map: THREE.ImageUtils.loadTexture('/Content/Images/dice-6-hi.png')
       })
    ];
    dice = new THREE.Mesh(
        new THREE.CubeGeometry(562, 562, 562, 1, 1, 1, materials),
        new THREE.MeshFaceMaterial());
    scene.add(dice);

}

function animate() {
    requestAnimationFrame(animate);
    dice.rotation.x += .05;
    dice.rotation.y += .05;
    dice.rotation.z += .05;
    renderer.render(scene, camera);
}

我遇到的错误是

Uncaught TypeError: Cannot read property 'map' of undefined 

来自three.js的第19546行(不是min版本),其中包含bufferGuessUVType(material)函数 - material未定义。这让我相信我的一个或所有材质定义存在问题。

使用的是three.js r58版本。

此时真的没有HTML或CSS,只有JS。

我可以轻松地让一个立方体旋转,并在其六个面上显示相同的图像,但不能使用不同的图像。这些图像只是骰子点数1-6的图像。

如果需要,稍微再给我一点时间,我可以做一个示例。

1个回答

39

编辑:THREE.MultiMaterial已过时。现在您可以直接将材质数组传递到构造函数中。像这样:

dice = new THREE.Mesh( new THREE.BoxGeometry( 562, 562, 562, 1, 1, 1 ), materials );

scene.add( dice );

注意不要直接从网络上复制老旧的示例。

升级到当前版本时,请始终检查Migration Wiki以获取帮助。

three.js r.85


魔术!!我想知道为什么three.js的文档中CubeGeometry构造函数没有7个参数。干杯! - OJay
7
讽刺的是,迁移维基链接本身已经失效了。 :P - erik258
这在使用 GLTFLoader 加载的对象上无法工作。 - CodeDezk
@CodeDezk 需要为材料设置特定的位置来建立网格,而来自其他来源的任意模型可能没有像BoxGeometry那样的位置。您可能需要另外提出一个问题来解决这个问题。 - Don McCurdy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接