Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Resolved Elements float on screen when using RuntimePanelUtils.CameraTransformWorldToPanel

Discussion in 'UI Toolkit' started by pawelduda, Nov 14, 2022.

  1. pawelduda

    pawelduda

    Joined:
    Feb 1, 2019
    Posts:
    45
    I'm rendering some VisualElements that are positioned in world space, above game objects.
    Here is a method that is called in each Update.

    Code (CSharp):
    1.     private void UpdatePosition(VisualElement item, Vector3 anchor) {
    2.       var root = _underlay.Root;
    3.       if (item.panel != null) {
    4.         var position = RuntimePanelUtils.CameraTransformWorldToPanel(root.panel, anchor, Camera.main);
    5.         item.transform.position = new Vector2(position.x - root.layout.width / 2,
    6.                                               position.y - root.layout.height / 2);
    7.       }
    8.     }
    Item is the small VisualElement I try to position.
    Anchor is world space position, where it should be placed. It doesn't change over calls.
    _underlay is a wrapper for an invisible uxml, that is stretch over whole screen.

    Everything is working well except when I move the camera - then items floats around the anchor point. It stops at anchor whenever I stop moving camera.

    Her is a gif of this behavior. In game it is much bigger - due to faster camera movement. Notice the element with yellow question mark strangely floating when camera is moved. When camera stops, it snaps in place.

    Anim2.gif

    Am I doing it wrong? Or is it due to differences in UI and Update update times?
    Is there a better way to do it?
     
  2. SimonDufour

    SimonDufour

    Unity Technologies

    Joined:
    Jun 30, 2020
    Posts:
    515
    It seems like it is just a reference to the previous frame position instead of the new position. You are possibly updating the position of the UI in a monobehavior whose update is called before the one moving the physical object. Instead of changing the script execution order, I think you could try moving the call to UpdatePosition in a lateUpdate.
     
  3. pawelduda

    pawelduda

    Joined:
    Feb 1, 2019
    Posts:
    45
    That was it, indeed! Thanks!
     
    SimonDufour likes this.