0
\$\begingroup\$

I want to have a GUI float over a game object using WorldToScreenPoint, similar to this tutorial. However, I am experiencing strange behavior with the GUI. I assume that this is due to the character's movement. I have already tried using Screen Space - Overlay and have kept a constant pixel size.

void Update() {
    Vector3 loc = transform.position;
    Collider[] colliders = Physics.OverlapSphere(loc,Radius);
    foreach (Collider hit in colliders){
        if(hit.gameObject.tag == "Player"){
            pressgui.transform.position = Camera.main.WorldToScreenPoint(transform.position);
        }
    }
}

Here is a video showing the problem.

\$\endgroup\$
0

1 Answer 1

0
\$\begingroup\$

The video tutorial you're following is relying on using a very particular canvas setup to create a coincidental alignment between the UI's world space and screen space coordinates. Since you have not configured your canvas in exactly the same way (we can't tell you how yours differs because you did not show us), this coincidence doesn't align so neatly for you. This is why you get non-sensical results from assigning a screen space position to a world space transform.

Fortunately, Unity has utility functions for converting between screen space and UI coordinates more robustly:

// In the inspector, set this to the layer the player object
// (and only the player) is on.
public LayerMask playerLayer;

void Update() {
    // Use a layer rather than a tag to distinguish your player,
    // for more efficient physics checks - allocation free!
    if (Physics.CheckSphere(transform.position, radius, playerLayer)) {
        // No need for a loop anymore.
        var screenPosition = Camera.main.WorldToScreenPoint(transform.position);

        RectTransformUtility.ScreenPointToLocalPointInRectangle(
            (RectTransform)pressgui.transform.parent, // pressgui's container
            screenPosition,          // position measured in pixels
            null,                    // use this for Screen Space - Overlay canvas
            out Vector2 uiPosition;  // local UI space position
        )

       // You may want to use anchoredPosition instead, 
       // depending on your anchor setup (which you have not shown us).
       pressgui.transform.localPosition = uiPosition;
    }
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .