1

I am wondering using A-frame (https://aframe.io) how I can get a user to exit vr mode if they're in vr mode when a function called myFunction() occurs. Just for clarification. When a function called myFunction() occurs, if the user isn't in vr mode, there won't we an effect but if the user is in vr mode, they will be exited from vr mode. How can this be done?

Mugen87
  • 28,829
  • 4
  • 27
  • 50
Aidan Young
  • 554
  • 4
  • 15

3 Answers3

2

Assuming you have a reference to the renderer, you should be able to do the following:

async function exitXR( renderer ) {

  const session = renderer.xr.getSession();

  if ( session !== null ) {
    
    await session.end();

    // execute optional code after WebXR shutdown
  
  }

}

Mugen87
  • 28,829
  • 4
  • 27
  • 50
  • I tested out the code with a basic scene and set the function to occur after 5 seconds and didn't achieve any results. Is there a code example of this? – Aidan Young Jul 22 '21 at 03:10
  • Yes, the `end()` method is used in this example: https://threejs.org/examples/webxr_vr_handinput_pointerclick. It worked for me as expected when I tested it last time with my Quest 2. – Mugen87 Jul 22 '21 at 07:55
  • The code example works but this is using three.js. I'm looking for an answer using A-frame. Do youknow if it's possible this works using A-frame? – Aidan Young Jul 22 '21 at 16:13
  • A-frame internally uses `three.js` so I would say yes. However, I don't know how to integrate the code into A-frame. – Mugen87 Jul 22 '21 at 17:13
  • I've had this issue in the past where I need to use three.js with A-frame and usually end up writing a custom component. This time I'm unsure of how it could work in my scene though. – Aidan Young Jul 22 '21 at 17:15
2

This code worked for me,

import {useThree} from "@react-three/fiber";

const ABC = ({ x, y, x}) => {

    const { gl } = useThree();

    const exitXR = async (gl) => {
        const session = gl.xr.getSession();
        if ( session !== null ) {
            await session.end();
        }
    }
    
return (
        <group>
            <Html>
                <div onClick={()=>exitXR(gl)}> EXIT </div>
            </Html>
        </group>
    )
}
Thushara Buddhika
  • 1,652
  • 12
  • 14
2

In A-Frame you can detect if the user is in vr or not with :

sceneEl.is('vr-mode')

https://aframe.io/docs/1.3.0/core/scene.html#states

Then just exit vr with the exitVR() method :

sceneEl.exitVR()

https://aframe.io/docs/1.3.0/core/scene.html#methods

You can get the sceneEl with:

const sceneEl = document.querySelector('a-scene');

In conclusion, just do:

const sceneEl = document.querySelector('a-scene');
if (sceneEl.is('vr-mode')) sceneEl.exitVR();
Synn
  • 1,118
  • 7
  • 11