How to listen to changes in the rotation of the ca

2019-02-25 12:43发布

Is there a way to add a listener on the current angle of view?

In other words, I'd like to trigger a function every time the user looks behind him.

The quickest way seems to be having a listener that checks the current head rotation and trust triggers the function if is within a certain range of degrees

标签: aframe
1条回答
forever°为你锁心
2楼-- · 2019-02-25 12:59

Edit

The componentchange event is throttled. And it is more performant to not go through the event system for frequent updates. The camera rotation always changes every frame in VR so there is no need to think whether the camera has changed. So we read rotation every frame with component tick.

AFRAME.registerComponent('rotation-reader', {
    tick: function () {
        var rotation = this.el.getAttribute('rotation');
        if (rotation.y < 180) {
            // ...
        }
    }
  });

// <a-camera rotation-reader>

Original

https://aframe.io/docs/0.2.0/core/entity.html#listening-for-component-changes

You can use the componentchanged event to listen to changes in the rotation:

document.querySelector('[camera]').addEventListener('componentchanged', function (evt) {
  if (evt.name !== 'rotation') { return; }
  if (evt.newData.y < 180) { // ... }
});

Or better as a component (this will trigger an event when rotation is certain amount):

AFRAME.registerComponent('trigger-on-look-behind', {
  schema: {type: 'string'},

  init: function () {
    var eventName = this.data;
    this.el.addEventListener('componentchanged', function (evt) {
      if (evt.name !== 'rotation') { return; }
      if (evt.newData.y < 180) {
        this.emit(eventName);
      }
    });
  }
});

And then:

<a-camera trigger-on-look-behind="looked-behind"></a-camera>
查看更多
登录 后发表回答