Search code examples
aframe

Get position of upper left corner of field of view


I want to be able to place an entity in the upper left corner of the view port. It is easy to hardcode the positioning, but of course this breaks for different screen sizes. Is there a way to get the xy coordinated of the upper left corner of the what is visible in the camera. I.e. what is the x distance from the center of the screen to the edge and what is the y distance from the center to the top?


Solution

  • Here is my solution, which allows you to fix an aframe element in the camera's view based on screen coordinates.

    const visibleHeightAtZDepth = ( depth ) => {
      const camera = AFRAME.scenes[0].camera;
      // compensate for cameras not positioned at z=0
      const cameraOffset = camera.position.z;
      if ( depth < cameraOffset ) depth -= cameraOffset;
      else depth += cameraOffset;
    
      // vertical fov in radians
      const vFOV = camera.fov * Math.PI / 180; 
    
      // Math.abs to ensure the result is always positive
      return 2 * Math.tan( vFOV / 2 ) * Math.abs( depth );
    };
    
    const visibleWidthAtZDepth = ( depth ) => {
      const camera = AFRAME.scenes[0].camera;
      const height = visibleHeightAtZDepth( depth, camera );
      let width = height * camera.aspect;
      return width;
    };
    
    const setHudPosition = ( fovWidth, fovHeight, depth) => {
      document.getElementById('hud').object3D.position.set(-fovWidth/2, fovHeight/2, depth);
    }
    
    setHudPosition(visibleWidthAtZDepth(-1), visibleHeightAtZDepth(-1), -1);
    

    You can use the height and width functions to get the visible field of view at arbitrary depths.