将对象的位置用于帧中的事件

Using an Object's postion for an Event in AFrame

我正在尝试制作一个组件来检查 AFrame 场景中球体的当前位置,以及它何时到达特定坐标以及何时触发事件(在下面的示例中,它将其重置为默认值位置):

AFRAME.registerComponent("trackball", {
  update: function() {
    let pos = this.el.getAttribute("position");
    if (pos == {x:-21.821,y: 1,z: 0})
      {
        this.el.setAttribute("position", "-21.821 5 0");
      }
  }
});

我不确定调用 .getAttribute("position") 时返回的是什么格式,所以这可能就是它不起作用的原因。我是运行 AFrame 1.1.0.

首先通过setAttribute()更改属性时调用update。如果您想要在每个渲染帧上调用的函数,请使用 tick().

其次,尝试使用范围,而不是固定点,对象很可能会移动超过两个刻度之间的点。

像这样:

<script src="https://aframe.io/releases/1.1.0/aframe.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/n5ro/aframe-physics-system@v4.0.1/dist/aframe-physics-system.min.js"></script>
<script>
AFRAME.registerComponent("trackball", {
  tick: function() {
    let pos = this.el.getAttribute("position");
    if (pos.y < 0.5) {
        // reset position
        this.el.setAttribute("position", "0 3 -4")
        // sync
        this.el.components["dynamic-body"].syncToPhysics();
      }
  }
});
</script>
<a-scene physics cursor="rayOrigin: mouse">
  <a-sphere position="0 1.25 -5" radius="0.25" color="#EF2D5E" dynamic-body trackball></a-sphere>
  <a-plane position="0 0 -4" rotation="-90 0 0" width="4" height="4" color="#7BC8A4" static-body></a-plane>
  <a-sky color="#ECECEC"></a-sky>
</a-scene>

在处理频繁调用的函数(当然适用于 tick())时,也尝试使用 object3D 属性代替 setAttribute()getAttribute()

<script src="https://aframe.io/releases/1.1.0/aframe.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/n5ro/aframe-physics-system@v4.0.1/dist/aframe-physics-system.min.js"></script>
<script>
  AFRAME.registerComponent("trackball", {
    // iife to initialize the "origin point" once
    tick: (function() {
      const origin = new THREE.Vector3(0, 3, -4);
      const y_range = 0.5;
      return function() {
        // check if the ball is out of range
        const pos = this.el.object3D.position
        if (pos.y < y_range) {
          // reset position
          pos.copy(origin);
          // sync
          this.el.components["dynamic-body"].syncToPhysics();
        }
      }
    })()
  });
</script>
<a-scene physics cursor="rayOrigin: mouse">
  <a-sphere position="0 1.25 -4" radius="0.25" color="#EF2D5E" dynamic-body trackball></a-sphere>
  <a-plane position="0 0 -4" rotation="-90 0 0" width="4" height="4" color="#7BC8A4" static-body></a-plane>
  <a-sky color="#ECECEC"></a-sky>
</a-scene>

请记住,以这种方式更新位置的性能更高,但会导致 getAttribute("position") 到 return 通过 setAttribute("position", new_position)

设置的最后位置