【问题标题】:Is there a smart way to reset the color of an object?有没有一种聪明的方法来重置对象的颜色?
【发布时间】:2021-03-02 18:03:28
【问题描述】:

我正在用 typescript 编写一个程序,我有 n 对象,默认颜色为红色,例如cupe.material.color 是红色的。

现在我想改变立方体的颜色,例如推ArrowUP。到目前为止我没有问题。 目标是当我更改对象 x 的颜色时,如果我设置另一个对象的颜色,它应该重置。只有一个对象应该有非默认颜色。

我的想法是创建一个保存初始颜色的变量,但这不起作用,看看:

var box1 = new THREE.Mesh(
  new THREE.BoxGeometry(),
  new THREE.MeshBasicMaterial({color:0xffffff})
); 

var box2 = new THREE.Mesh(
  new THREE.BoxGeometry(),
  new THREE.MeshBasicMaterial({color:0xffffff})
);
var back;
window.addEventListener("keydown",function(event){
   if(event.key == "ArrowUp") {
      box1.material.color.set("red");
      back = box1
      
    }
    if(event.key == "s") {
      box2.material.color.set("red");
      back.material.color.set("0xffffff")
      back = box2
    }
}

【问题讨论】:

    标签: typescript three.js


    【解决方案1】:

    您可以在其userData 属性中存储材质对象的任意值。所以试试这个:

    box1.material.userData.originalColor = new THREE.Color( 0xffffff );
    
    // later when you want to perform the reset
    
    box1.material.color.copy( box1.material.userData.originalColor );
    

    【讨论】:

    • 嘿,但是如果您知道更改的对象,这才有效。如果我有 20 个对象,那么这将是一个问题,或者?顺便说一句,感谢您的快速回答。
    • 不,因为每个材质对象都有自己的originalColor 值。
    • 它们都具有相同的默认颜色。我在这里看到的问题是,我必须使用所有 20 多个对象来处理它,对于 100 个对象,每个 if 语句中的代码将是 100 行
    【解决方案2】:

    你可以把你的对象放在一个数组中,然后循环遍历它,恢复颜色,然后突出显示你需要的对象(使用通常的数字键 0-9(不在数字键盘上)):

    body{
      overflow: hidden;
      margin: 0;
    }
    <script type="module">
    import * as THREE from "https://threejs.org/build/three.module.js";
    
    let scene = new THREE.Scene();
    let camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 100);
    camera.position.set(0, 0, 20);
    let renderer = new THREE.WebGLRenderer();
    renderer.setSize(innerWidth, innerHeight);
    document.body.appendChild(renderer.domElement);
    
    let highlight = 0xffffff;
    let boxes = [];
    for(let i = 0; i < 10; i++){
      let g = new THREE.BoxBufferGeometry();
      let m = new THREE.MeshBasicMaterial();
      let c = Math.random() * 0x7f7f7f + 0x7f7f7f;
      m.color.set(c);
      m.userData.color = c;
      let box = new THREE.Mesh(g, m);
      box.position.x = (-4.5 + i) * 2;
      boxes.push(box);
      scene.add(box);
    }
    
    document.addEventListener("keydown", event => {
      resetColors();
      boxes[event.keyCode - 48].material.color.set(highlight);
      
    });
    
    renderer.setAnimationLoop(()=>{
      renderer.render(scene, camera);
    });
    
    function resetColors(){
      boxes.forEach(b => {b.material.color.set(b.material.userData.color)});
    }
    </script>

    【讨论】:

      猜你喜欢
      • 2020-08-28
      • 2015-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-19
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多