在 "AR.JS" 中更改对象(.dae 或 gltf)的颜色

Change the color of an object (.dae or gltf) in "AR.JS"

我正在尝试更改我在搅拌机中创建的对象的颜色。我可以在 html 代码本身中更改对象的颜色,例如 "a-box, a-sphere",但是对于 tree.js(gltf 或 .dae - collada)中的对象,我不能。

CodePen(这只是一个测试环境,供以后在我的实际项目中应用(AR.JS))

<html>

<head>
  <script src="https://aframe.io/releases/0.7.0/aframe.min.js"></script>
</head>

<body>
  <a-scene>

    <a-gltf-model id="test" src="https://raw.githubusercontent.com/KurtRodrigues/KurtRodrigues.github.io/master/Arquivos%20utilizados/Pe%C3%A7a%2Bbancada_V2.gltf" color="#FF0000" position="0 0 -3" rotation="0 0 0" scale="1.5 1.5 1.5" size="20px"> </a-gltf-model>

    <a-sky color="#ECECEC"></a-sky>
  </a-scene>
</body>

</html>

已经尝试过:

HTMLcolor= # ff00000

CSS 按 id .test {color: # ff0000}

JS:

var b = document.querySelector ("test");
b.setAttribute ("color", "red");

有什么方法可以直接在代码中或在我制作对象(搅拌器)时更改对象的颜色?

包含 GLTF 模型的实体很复杂,因为它们在 gltf 容器中包含许多模型。您不能像使用其他基元那样在 gltf 内的模型上使用 setAttribute。相反,您必须像对待三个 js 模型一样对待它们。这意味着您需要制作一个自定义组件,该组件将 'traverse' 通过 gltf,并找到模型,并存储对它们的变量引用,然后您可以在 THREEjs 级别更改这些模型的参数。例如

AFRAME.registerComponent('treeman', {
        init: function(){
            let el = this.el;
            let self = this;
            self.trees = [];              
            el.addEventListener("model-loaded", e =>{
                let tree3D = el.getObject3D('mesh'); // get the THREEjs group
                if (!tree3D){return;}    
              console.log('tree3D', tree3D); // log the THREEjs group so you can look 
                                          at all of its contents and parameters.
                tree3D.traverse(function(node){ // this is how you loop through 
                                                  (traverse) the models
                    if (node.isMesh){   
                      console.log(node);
                        self.trees.push(node);
                      if(node.name == "Trunk_A"){
                        self.treeMat = node.material; // store a reference to the 
                                         material you want to modify later
                      }
                      node.material.map = null; // removes the texture so we can see 
                               color clearly
                    }
                });
          });

稍后,您可以使用事件侦听器功能访问此组件,并对材料进行处理。像这样

 el.addEventListener('changecolor', e =>{               
            let colorp = e.detail.color;
            let colorHex = Number(colorp.replace('#', '0x'));
            let color3D = new THREE.Color(colorHex);
            self.treeMat.color = color3D;                
          });

请注意,我们必须将颜色放入 THREEjs 需要的数据结构中,例如颜色对象。与 Aframe 的简单性相比,所有这些都是很多工作,但您拥有更多的控制权,并且可以准确地看到幕后发生的事情。

glitch here.