Raycaster相交的glb模型儿童事件

时间:2019-11-11 15:59:39

标签: three.js aframe raycasting gltf

我正在加载glb模型,如下所示:

<a-scene>
    <a-assets>
        <a-asset-item id="tree" src="/path/to/tree.gltf"></a-asset-item>
    </a-assets>
    <a-entity gltf-model="#tree"></a-entity>
</a-scene>

我正在通过JavaScript中的querySelector选择模型,并将raycaster相交的事件附加到modelEl。但是,当我从glb模型中的一个子节点悬停到另一个子节点时,不会触发此事件。任何人都可以帮助我。

1 个答案:

答案 0 :(得分:3)

此方法适用于原始实体,但gltf-model实体的用法有所不同。那是因为gltf-model实体包含许多子对象,因此您需要编写一个自定义组件以获得对要与raycaster相交的模型的引用,并测试它们的相交。在该组件中,您可以使用遍历遍历所有子模型,例如

import moxios from 'moxios'; // you have to npm install moxios
import api from './path/to/api.js';
import businessList from './path/to/business_list.json';

it('...', () => {
  // Install the axios instance the api module is exporting
  moxios.install(api);

  moxios.stubRequest(new RegExp('.*?/api/comapines.*'), {
    status: 200,
    response: { data: businessList }
  });


  // Test body...
  // Any axios call to an endpiont that matches the regExp would always return the response specified

  moxios.uninstall();
})

然后,您可以像这样与“ raycaster相交”事件侦听器进行相交测试

 AFRAME.registerComponent('treeman', {
            init: function(){
                let el = this.el;
                let self = this;
                self.trees = [];              
                el.addEventListener("model-loaded", e =>{
                    let tree3D = el.getObject3D('mesh');
                    if (!tree3D){return;}    
                  //console.log('tree3D', tree3D);
                    tree3D.traverse(function(node){
                        if (node.isMesh){   
                          console.log(node);
                          self.trees.push(node);                          
                          node.material = new THREE.MeshStandardMaterial({color: 0x33aa00});
                        }
                    });
              });

然后在点击事件上执行类似的操作

  el.addEventListener('raycaster-intersected', e =>{  
                self.raycaster = e.detail.el;
                let intersection = self.raycaster.components.raycaster.getIntersection(el);
                  console.log('click', intersection.object.name, self.mouseOverObject, 
                            intersection.object.name != self.mouseOverObject );  
                if (self.mouseOverObject != intersection.object.name){
                  intersection.object.material.emissive = new THREE.Color(0xFFFF00);
                  intersection.object.material.emissiveIntensity = 0.5; 
                } else {
                   intersection.object.material.emissive = new THREE.Color(0x000000);
                  intersection.object.material.emissiveIntensity = 0.0; 
                }                  
                  self.mouseOverObject = intersection.object.name;
              });

这是Moxios