首页 > 解决方案 > 将对象的位置用于 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。

标签: javascripthtmlthree.jsaframe

解决方案


首先在update通过 更改属性时调用setAttribute()。如果您想要在每个渲染帧上调用的函数,请使用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>

在处理频繁调用的函数(当然适用于)时,也可以尝试使用object3D属性:setAttribute()getAttribute()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", {
    // 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")通过返回最后一个位置设置setAttribute("position", new_position)


推荐阅读