【问题标题】:Can a keyboard event be captured on an aframe entity可以在框架实体上捕获键盘事件吗
【发布时间】:2018-02-13 14:27:15
【问题描述】:

是否可以在 AFRAME 实体上捕获特定的键盘按键事件?

我通过实体上的 addEventListener 进行了尝试,但似乎事件不会传播到实体(有和没有 wasd-controls)。

    AFRAME.registerComponent('listenonclick', {
    ...
    init: function () {
    ...
        this.el.addEventListener('keydown', function(event) {
           console.log("onkeydown Button" + event.code);
        });
    ...
    <a-box listenonclick id='box1' ..."></a-box>

但是,当将事件添加到窗口而不是实体时,它将被触发。

【问题讨论】:

    标签: javascript three.js aframe


    【解决方案1】:

    这是一种方法:将这段代码添加到之前 a-scene

    document.addEventListener('keydown', function(event) {
      document.querySelectorAll('.listenonkey').forEach(function(obj){
        obj.setAttribute('position', '0 0 0');
      });
    });
    

    然后

      <a-entity class='listenonkey' .... other stuff... </a-entity>
    

    实际上,此解决方案将向 HTML 文档添加一个额外的 key even 处理程序,类似于 aframe 的做法,然后 onkeydown 移动它们。

    我还没有在 aframe 文档中找到如何更优雅地做到这一点。

    【讨论】:

    • 感谢代码,完美运行,效率很高!同时,我采用 cursor.js 代码来实现类似的行为,以确保只有光标指向的对象才会接收事件。
    【解决方案2】:

    我更喜欢将 onkeydown 事件绑定到 aframe 方法。这样,您可以更有效地利用两种方式绑定。示例

    computed: {
        computed_pos: function () {      
          return `${this.xpos} 1 -2`;
        }
      },
    methods: {
         OnKeyDown:function(e){
           if(e.key == "ArrowLeft"){
             this.xpos-=10;
           }
           else if(e.key == "ArrowRight"){
             this.xpos+=10;
           }
           
         }   },   
    created: function(){      
           window.addEventListener('keydown', this.OnKeyDown);         
    },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-01
      相关资源
      最近更新 更多