首页 > 解决方案 > 制作一个按钮来移动一个对象

问题描述

我正在制作一个 A-Frame 站点,我需要创建一个按钮来将一个带有 id:"test" 的球移动到它的起始位置:0 8 0。我已经尝试使用 setAttribute 脚本,但它不起作用。这是我目前正在使用的 javascript 代码:

AFRAME.registerComponent('ballreset', {
  events: {
    click: function(evt)
    {
      document.getElementById('test').setAttribute('position', {x:0, y:8, z:0});
      
    }
  }
});

编辑:我在代码中发现了一个错字。但是没有解决问题

标签: javascriptthree.jsaframe

解决方案


没有一个完整的例子,很难说到底是什么问题,但是,

  • 确保您确实有一个基于 raycaster 的光标组件。鼠标点击不能像处理 HTML 元素那样处理 webGL 渲染。
  • 确保点击监听器正在工作,即。通过记录每次点击
  • 确保给定的元素id在点击时存在

以下是与您想要实现的目标类似的工作版本(单击任何对象):

<script src="https://aframe.io/releases/1.1.0/aframe.min.js"></script>
<script>
  AFRAME.registerComponent('foo', {
    events: {
      click: function(evt) {
        // grab the current position
        let pos = this.el.getAttribute("position");
        // move upwards
        this.el.setAttribute('position', { x: pos.x, y: pos.y + 0.25, z: pos.z });
      }
    }
  });
</script>
<!-- attach a cursor component -->
<a-scene cursor="rayOrigin: mouse">
  <a-box position="-1 0.5 -3" rotation="0 45 0" color="#4CC3D9" foo></a-box>
  <a-sphere position="0 1.25 -5" radius="1.25" color="#EF2D5E" foo></a-sphere>
  <a-cylinder position="1 0.75 -3" radius="0.5" height="1.5" color="#FFC65D" foo></a-cylinder>
  <a-plane position="0 0 -4" rotation="-90 0 0" width="4" height="4" color="#7BC8A4" foo></a-plane>
  <a-sky color="#ECECEC"></a-sky>
</a-scene>


推荐阅读