Skip to main content
2 of 2
edited tags
Mugen87
  • 31.2k
  • 4
  • 34
  • 61

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?

Zack Lee
  • 3.2k
  • 7
  • 45
  • 96