Floating UI Help

Hello,

I’m working on positioning my UI directly above the center of my character. While it looks fine when the character is at the center of the camera’s perspective, there’s an issue when I move to the far left or right of the camera’s perspective. I’ve attached two screenshots to help visualize the issue. Could someone help me address this problem? For additional context, target is set to the player’s transform, camera is the main camera, and the canvas is the scene’s canvas which is set to overlay.

Please also note that this script was quickly made so the naming and lack of use for some variables will be altered once I iron out this issue. Here’s the script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class PlayerFloatingUI : MonoBehaviour
{

    [Header("UI Settings")]
    [SerializeField] private Vector3 offset;
    [SerializeField] private Canvas canvas;
    [SerializeField] private Camera cam;
    [SerializeField] private Transform target;

    [Header("UI Prefabs")]
    [SerializeField] private Image xBtnPrefab;
    [SerializeField] private Image xAtnPrefab;

    private Image uiUse;

    // Start is called before the first frame update
    void Start()
    {
        uiUse = Instantiate(xBtnPrefab, canvas.transform).GetComponent<Image>();
    }

    // Update is called once per frame
    void Update()
    {

        uiUse.transform.position = cam.WorldToScreenPoint(target.position + offset);

    }


}


Here are alternative screenshots. Better display the issue I’m having.


I think the UI is positioned “correctly”: If you would draw a line in 3D from the center of your character upwards it would go through the center of your UI. But, that is obviously not what you want here. Instead, the bottom-center of your UI should be above the characters center and “above” should be moving vertically on the screen.

To achieve that you could:

  • Get the screen coordinates of the character’s center

  • Add half of the UI height

  • Add a vertical offset to make it float above the character

Compared to your approach, this will add the offsets in screen-space where “above” will always move vertically on the screen (which is not true for offsets added in 3D)
Just be aware that if your camera moves, this approach might not work. Then you might have to scale the offset or use a 3D offset again. In that case it can get a little complicated. I experimented a lot while working on my Unity asset. But your camera looks like a non-moving one to me, so this should hopefully work.