如何通过实体的 setAttribute 正确添加和删除游标组件?

How to properly add and remove a cursor component via entity's setAttribute?

根据 ngokevin 在上一个问题中建议的有益方法更改,我现在尝试在两个实体(每个实体都是单独相机的子实体)之间交换光标组件。但是,我看到了两种出乎我意料的行为:

在第一个案例解决该问题后,我可以验证简单地调用 .removeAttribute('raycaster') ,我不太确定是什么阻止了添加游标的工作。这是第二个演示的所有组件:

AFRAME.registerComponent( 'add-cursor-on-click', {
  init: function() {
    this.el.setAttribute('cursor'); 
    this.el.addEventListener( 'click', function() { console.log("Received click ev."); } );
  }
});

<a-entity id="onlyTheCursorAfterClick" add-cursor-on-click></a-entity>

一如既往,任何见解将不胜感激。

似乎最近添加了游标组件的删除生命周期处理程序,因此它目前只能在 master 上正确运行,请参阅此拉取请求:https://github.com/aframevr/aframe/pull/2397

游标组件也不会在其初始化时附加事件。它等待 render-target-loaded (https://github.com/aframevr/aframe/blob/2c0d9ed1efd93df841d207da5e7d2d69c67d8d3a/src/components/cursor.js#L50)

所以在你的组件的初始化中,如果你想删除光标组件,在组件的初始化中你需要:

if (!canvas) {
      this.el.sceneEl.addEventListener('render-target-loaded', this.init.bind(this));
      return;
}

http://codepen.io/jhsu/pen/XMJQmE

不过,如您所见,您仍然需要手动移除 raycaster

this.el.removeAttribute('raycaster');

要添加 cursor 组件,您需要为该组件传递数据

this.el.setAttribute('cursor', {}); 

原因是有一个undefinedcheck when instantiating a component.