Search code examples
javascriptthree.jsvirtual-reality

Unable to change camera position when using VRControls


I have the following code:

...
camera = new THREE.PerspectiveCamera(75, screenRatio, 1, 10000 );
camera.position.z = -10; // position.set(0, 0, -10) also not working.
controls = new THREE.VRControls( camera );
effect = new THREE.VREffect( renderer );
effect.setSize( window.innerWidth, window.innerHeight );
...

VRControls are working in sync with the accelerometer, but I can't change the cameras position. It seems stuck in the origin point (0,0,0). It was working just fine before applying VRControls and VREffect.


Solution

  • Found the solution inside Sechelt demo from Mozilla VR Team demos. I'll put here a code snippet as reference for other VR beginners.

    Adding the camera to a group instead of updating the camera position directly is the way to move the camera.

    var scene, renderer, cameraRatio, camera, controls, effect, dolly;
    
    function init() {
        scene = new THREE.Scene();
    
        renderer = new THREE.WebGLRenderer({ antialias: true });
        renderer.setSize( window.innerWidth, window.innerHeight );
        document.body.appendChild( renderer.domElement );
    
        cameraRatio = window.innerWidth / window.innerHeight;
        camera = new THREE.PerspectiveCamera( 75, cameraRatio, 1, 1000 );       
    
        controls = new THREE.VRControls( camera );
        effect = new THREE.VREffect( renderer );
        effect.setSize( window.innerWidth, window.innerHeight );
    
        // This helps move the camera
        dolly = new THREE.Group();
        dolly.position.set( 0, 0, 0 );
        scene.add( dolly );
        dolly.add( camera );
    
        ...
        // Of course, there should be lights, objects, etc
    }
    
    function animate() {
        dolly.position.x += 0.1;
        controls.update();
        effect.render( scene, camera );
    }
    
    init();
    animate();