首页 > 解决方案 > 三个 JS 将渐变应用于导入的模型

问题描述

以下两个球体之间的区别 - 就其渐变颜色的应用方式而言,归结为一种说法:

sphereGeometry = sphereGeometry.toNonIndexed();

在此处输入图像描述

在此处输入图像描述

因为我真的很喜欢.toNonIndexed()给我们带来的更平滑的外观,所以我尝试将它应用到 THREE.js GIT 上可用的一些导入的“.glb”模型 - 但它不起作用。

例如,当我使用此处提供的马模型时会发生以下情况:https ://github.com/mrdoob/three.js/blob/master/examples/models/gltf/Horse.glb

在此处输入图像描述

由于某种原因,它基本上完全忽略了我的颜色并默认为红色和黑色。

但是当我注释掉这.toNonIndexed()条线时,它给了我我要求的颜色 - 除了你肯定看到三角形,这是我试图避免的外观:

在此处输入图像描述

这是我加载对象的代码:

function loadAny3DModel() {
    loader.load("./Horse.glb", function(theHorse) {
       console.log("===>'theHorse' has arrived!!!\n");

       var horseScene = theHorse.scene;
       horseMesh = horseScene.children[0]; 
                
       var horseGeometry = horseMesh.geometry; 
       let horseMat = horseMesh.material;
       var horseVertexPositionsArray = horseGeometry.attributes.position;

       // Here's the command that isn't working:
       // horseGeometry = horseGeometry.toNonIndexed(); 
       // horseVertexPositionsArray = horseGeometry.attributes.position;

        let theColor = new THREE.Color();
        let colorsArray = [];
        for(let i = 0; i < horseVertexPositionsArray.count; i++) {
          let randC1 = "purple"; 
          let randC2 = "white";
          let chosenColor = i % 2 == 0 ? randC1 : randC2;
          theColor.set(chosenColor);
          colorsArray.push(theColor.r, theColor.g, theColor.b);
        }
        horseGeometry.setAttribute("color", new THREE.Float32BufferAttribute(colorsArray, 3));
        horseMat.vertexColors = true;

        render();
        scene.add(horseScene);

    }
}

我应该怎么做才能获得更平滑的渐变?

==================================================== ====================

更新:

这是我正在尝试做的一个非常粗略的想法:在整个模型上扩展渐变,而不是形成模型的每个三角形。(将此图像与上面的图像进行比较。)

在此处输入图像描述

标签: javascriptthree.js

解决方案


如果您在以下行中发表评论...

horseGeometry = horseGeometry.toNonIndexed();

...这意味着您创建了一个新的(!)几何。只要您不将几何图形分配回Mesh.geometry,此代码就不会产生任何影响。所以解决方法是在使用后添加以下行toNonIndexed()

horseMesh.geometry = horseGeometry;

推荐阅读