three.jswebxr

How to make a cube to always appear in front of the XR(phone) camera?


I'm trying to make a cube mesh to be always positioned in front of the XR camera.

No matter how I move my phone camera, the cube should appear right in front of the camera showing only one side of the cube.

Firstly, I added a cube mesh to the scene in the beginning:

material = new THREE.MeshLambertMaterial({ color: 0x9797CE });
box = new THREE.Mesh(new THREE.CubeGeometry(1, 1, 1), material);
box.position.set(0, 0, -3);
scene.add(box);

And then tried to draw the box in front of the XR camera:

function animate() {
    let xrCamera = renderer.xr.getCamera(camera);
    box.position.set(xrCamera.position.x, xrCamera.position.y, xrCamera.position.z - 3);
    box.rotation.set(xrCamera.rotation.x, xrCamera.rotation.y, xrCamera.rotation.z);
    renderer.render(scene, camera);
}

When I run the code, the cube appears in front of my phone camera.

But when I rotate my phone, the cube rotates itself in the same position not following the camera.

I also tried xrCamera.add(box) but it doesn't seem to work.

How can I correctly make the cube always appear still in front of the XR camera?


Solution

  • It's important to know that currently (r115) the transformation properties position, rotation and scale as well as the local matrix of the XR camera are not updated.

    So instead of adding the box to xrCamera, add it to camera. Besides, keep in mind that WebXRManager.getCamera() is intended for internal use only and no part of the public API.