Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix a flipped worldspace UI that face the player in unity?

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

public class Well : MonoBehaviour
{
    public int currentLiter = 5;
    public int maxWellCapacity = 10;

    public float refillTime = 8f;

    public Text wellDurText;
    public Image refillTimeText;
    public GameObject player;

    public void Update()
    {
        if (currentLiter < maxWellCapacity)
        {
            RefillWell();
        }

        wellDurText.GetComponent<Text>().text = currentLiter.ToString();
        wellDurText.transform.LookAt(player.transform);

        refillTimeText.GetComponent<Image>().fillAmount = refillTime/8;
        refillTimeText.transform.LookAt(player.transform);
    }

    void RefillWell()
    {
        refillTime -= Time.deltaTime;

        if (refillTime <= 0.0f)
        {
            currentLiter += 1;
            refillTime = 8f;
        }
    }
}

what I'm trying to do: wellDurText to face the player wherever the player is but for some reason, it's flipped. what I tried to do: I tried to flipped the UI manually from the editor but when I tried it in the game it just flipped back over.

like image 407
David Avatar asked Jan 24 '26 17:01

David


1 Answers

UI elements forward vector has to point away from the spectator. This is because usually the default forward direction used for e.g. 2D UI points into the display but you want to gave the UI the user sitting in front (or from Unity perspective behind ;) ) of the display.

When you are using

wellDurText.transform.LookAt(player.transform);

You tell it to point with its forward vector towards the player so it points in the exact wrong direction.


It rather should be e.g.

var direction = wellDurText.transform.position - player.transform.position;
var lookRotation = Quaternion.LookDirection(direction);
wellDurText.transform.rotation = lookRotation;

Same also for the RefillTimeText

like image 123
derHugo Avatar answered Jan 27 '26 08:01

derHugo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!