A-frame score counter with multiple objects

做~自己de王妃 提交于 2020-01-06 14:33:44

问题


I've looked at this answer: Implementing a score counter in A-Frame

... but cannot figure out how to write a similar function that would work for multiple objects, since querySelector only finds the first element.

I'm trying to create a scene with 5-8 objects, and each one can only be clicked once. When an object is clicked, the counter will increment by 1.


回答1:


Either use querySelectorAll:

var targets = querySelectorAll('a-box')`
for (var i = 0; i < targets.length; i++) {  // Add event listeners... }

But better, use a container entity that listens to the click events that bubble up.

<a-entity listener>
  <a-box data-raycastable></a-box>
  <a-box data-raycastable></a-box>
</a-entity>
<a-entity cursor="rayOrigin: mouse" raycaster="objects: [data-raycastable]"></a-entity>

Component:

AFRAME.registerComponent('listener', {
  init: function () {
    this.el.addEventListener('click', evt => {
      if (evt.target.dataset.wasClicked) { return; }
      // evt.target tells you which was clicked.
      evt.target.dataset.wasClicked = true;
      // Score up.
    });
  }
});

As a side note, state component is a great place to store your score. https://www.npmjs.com/package/aframe-state-component



来源:https://stackoverflow.com/questions/51108202/a-frame-score-counter-with-multiple-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!