Search code examples
aframe

Confusion with this on listener?


I have several entities in a scene the are externally triggered to be visible. When they are visible and a user mouses over them (gaze-based, so when the user looks at the entity), audio should be played that is unique to each entity. When the user looks elsewhere, the audio should stop.

The problem I am experiencing is that the listener in my custom component appears to not know which entity is playing when more than one object is open simultaneously, and will stop/start the wrong audio. How do I ensure that the listener is for the correct entity?

Referencing this: Play sound on click in A-Frame

js:

AFRAME.registerComponent('play-audio', {
init:function() {
let playing = false;
let audio = this.el.components.sound;

this.el.addEventListener('mouseenter', () => {
  var viz = this.el.getAttribute('material').visible;
  if (viz){
    if(!playing) {
      audio.playSound();
    } else {
      audio.stopSound();
    }
    playing = !playing;
  }

});
this.el.addEventListener('mouseleave', () => {
  audio.stopSound();
  playing = !playing;
})
}
})

example HTML:

<a-sound  id="popup1" data-clickable play-audio autoplay="false" loop="false" volume="5"  visible="false" src="#audio1">
</a-sound>

<a-sound  id="popup2" data-clickable play-audio autoplay="false" loop="false" volume="5"  visible="false" src="#audio2">
</a-sound>

Solution

  • The bindings look right.

    Is it because both sounds are getting intersected / looked at, at the same time? visibility doesn't toggle off the raycaster, I don't think. You can add / remove the data-clickable attribute.