使用对象ID的Raycast无法正常工作:threeJS

时间:2019-11-17 13:08:09

标签: javascript three.js raycasting

我正在尝试通过射线投射为模型的不同部分分配不同的标准材料,并使用其对象ID作为参考。但是,当我尝试将多个材质应用于同一模型的不同ID时,所有对象都显示相同的材质。无法区分ID。

相同的代码如下。

var intersects = raycaster.intersectObjects(scene.children, true);
if (intersects.length > 0) {

  for (var i = 0; i < intersects.length; i++) {
    if (intersects[i].object.id) {

      intersects[i].object.material = material1; /* standrad material */
      intersects[i].object.material.needsUpdate = true;
    }
  }

    /* I'm using the buttons to change the materials */

    $('.btn1').click(function() {
      for (var i = 0; i < intersects.length; i++) {
        intersects[i].object.material = material2;
        intersects[i].object.material.needsUpdate = true;
      }
    });

    $('.btn2').click(function() {
      for (var i = 0; i < intersects.length; i++) {
        intersects[i].object.material = material3;
        intersects[i].object.material.needsUpdate = true;
      }
    });
  }

2 个答案:

答案 0 :(得分:0)

这是一种构造这样的东西的方法:

function materialSwitchingTest(renderer,camera){

    var mouseVec = new THREE.Vector3();
    var mouse2D = new THREE.Vector3();
    var rawMouse2D = new THREE.Vector3();
    var intersections = []

    /* I'm using the buttons to change the materials */
    $('.btn1').click(function() {
        if(intersections.length>0) intersections[0].object.material = material1
    });

    $('.btn2').click(function() {
        if(intersections.length>0) intersections[0].object.material = material2
    });

    window.onmousedown=(e)=>{
        if(event.target !== renderer.domElement.parentElement)return
        var mx = event.layerX;
        var my = event.layerY;
        rawMouse2D.set(mx, my, 0);
        mouse2D.x = (mx / renderer.domElement.width) * 2 - 1;
        mouse2D.y = -(my / renderer.domElement.height) * 2 + 1;
        raycaster.setFromCamera(mouse2D,camera)
intersects = raycaster.intersectObjects(scene.children, true);
    }
}


materialSwitchingTest( yourRenderer, yourCamera )

答案 1 :(得分:0)

我已经解决了这个问题,我不得不改变自己的逻辑以适应要求。这就是我所做的。

if (intersects.length > 0) {


  if (intersected1 != intersects[0].object) {
    if (intersected1)
      intersected1 = intersects[0].object;
    intersected1.material = materialin;
    intersected1.material.needsUpdate = true;
  } else {
    if (intersected1) intersected1.material = material1;
    intersected1.material.needsUpdate = true;

    intersected1 = null;
  }

  $('.btn1').click(function() {
    intersected1.object.material = material1;
  });

  $('.btn2').click(function() {
    intersected1.material = material2;
  });