Search code examples
c#unity-game-engineuser-interfacemenuvirtual-reality

Make Canvas to follow the camera


I want an UI canvas to follow the camera so it will be in front of the head always and also interactable like VR menu. I'm using the following code to do so.

public class FollowMe : MonoBehaviour
{
    public GameObject menuCanvas;
    public Camera FirstPersonCamera;
    [Range(0, 1)]
    public float smoothFactor = 0.5f;

// how far to stay away fromt he center

    public float offsetRadius   = 0.3f;
    public float distanceToHead = 4;

    public  void Update()
    {
        // make the UI always face towards the camera
        menuCanvas.transform.rotation = FirstPersonCamera.transform.rotation;

        var cameraCenter = FirstPersonCamera.transform.position + FirstPersonCamera.transform.forward * distanceToHead;

        var currentPos = menuCanvas.transform.position;

        // in which direction from the center?
        var direction = currentPos - cameraCenter;

        // target is in the same direction but offsetRadius
        // from the center
        var targetPosition = cameraCenter + direction.normalized * offsetRadius;

        // finally interpolate towards this position
        menuCanvas.transform.position = Vector3.Lerp(currentPos, targetPosition, smoothFactor);
    }
}

Unfortunately, the canvas is flickering in front fo the camera and it is not properly positioned. How do I make the menu to follow the camera?|


Solution

  • If there is no reason against it you can use a ScreenSpace - Camera canvas as stated in the docs. Then you can reference your FPS camera as the rendering camera for the canvas.