Search code examples
three.jscameravirtual-realityaframewebvr

aframe camera switch between exit vr and enter vr


how is it possible to switch between the camera on desktop and VR? i wanna use the mouse-cursor on desktop and when i enter VR it should switch to another camera with cursor-fusing.

here is my code:

<a-entity id="cam-desktop" camera="userHeight: 1.6; zoom:1 " look-controls mouse-cursor>
</a-entity>


<a-entity id="cam-vr" camera="userHeight: 1.6; zoom:1 " look-controls>
    <a-animation begin="cursor-fusing" delay=" 3000" attribute="camera.zoom" from="1" to="4" dur="1000"></a-animation>
  <a-animation begin="click" delay="500" attribute="camera.zoom" from="4" to="1" dur="1000"></a-animation>
    <a-entity cursor="fuse: true; fuseTimeout:4000" geometry="primitive: ring; radiusInner: 0.02; radiusOuter: 0.03; thetaLength: 360; thetaStart: 0" rotation="0 0 90" position="0 0 -1" material="color: black; side: double; shader: flat">
    <a-animation begin="cursor-fusing" attribute="geometry.thetaLength" from="360" to="0" easing="linear" dur="3000"></a-animation>
    <a-animation begin="mouseleave" attribute="geometry.thetaLength" from="360" to="360" dur="0"></a-animation>
    </entity>
</a-entity>

thank you very much!


Solution

  • You can create a component, which listenes to the 'enter-vr' and 'exit-vr' events, and set the active camera accordingly:

    AFRAME.registerComponent('scenelistener',{
       init:function(){
          let vrcam = document.querySelector("#cam-vr");
          let dcam = document.querySelector("#cam-desktop");
          let  vrmode = false;
          this.el.sceneEl.addEventListener('enter-vr',function(){
               if(!vrmode){
                   dcam.setAttribute('active',false);
                   vrcam.setAttribute('active',true);
                   vrmode!=vrmode;
               }
          }
          this.el.sceneEl.addEventListener('exit-vr',function(){
               if(vrmode){
                   dcam.setAttribute('active',true);
                   vrcam.setAttribute('active',false);
                   vrmode!=vrmode;
               }
          }
      }
    });
    

    Actually, You can just paste the listeners anywhere, moreover You could just listen to any event and do stuff accordingly to the received event, I just wanted to show You the concept.
    Im not sure what happens if 2+ camera's are active, so i made them false on change.
    UPDATE
    I did not see that the cameras are entities, not primitives, so You have to set the attribute like this: setAttribute('camera','active',true)
    I have some issues with the cursor, so i make it visible and invisible, depending on the vr state.
    Working fiddle ( at least the camera switch ) here.