Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen to changes in the rotation of the camera in A-Frame?

Tags:

aframe

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

like image 773
ngokevin Avatar asked Aug 11 '16 23:08

ngokevin


1 Answers

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>
like image 53
ngokevin Avatar answered Jan 03 '23 10:01

ngokevin