Search Unity

Question How to maintain same relative position of parent and child

Discussion in 'UI Toolkit' started by VoodooDetective, Oct 3, 2022.

  1. VoodooDetective

    VoodooDetective

    Joined:
    Oct 11, 2019
    Posts:
    239
    For context, this is for a Drag & Drop with Panning widget. So you can drag an element to the edge of the screen, and the parent element with start to pan.

    I have two VisualElements, a parent with Scale(0.5,0.5,1) and a child with Scale(1,1,1). I want to move the parent 10px right and 10px down.

    So here's what I do:
    Code (CSharp):
    1. parent.style.position = Position.Absolute;
    2. parent.style.left = 10;
    3. parent.style.top = 10;
    But the parent has a child:
    Code (CSharp):
    1. Parent - Scale(0.5,0.5,1)
    2. {
    3.     Child- Scale(1,1,1)
    4.     {
    5.  
    6.  
    7.     }
    8. }
    I would like the child to remain in the same relative position on screen after I change the parent's position. In other words, I'd like the child to occupy the exact same pixels on screen as it did before the position change of its parent.

    How can I do this? Here's what I've tried:
    Code (CSharp):
    1. Vector2 panSpeed = new Vector2(10,10);
    2. parent.transform.scale = new Vector2(0.5,0.5);
    3. parent.transform.position = parent.transform.position + panSpeed;
    4.  
    5. Vector2 localSpeed = panSpeed / m_PanElement.WorldScale();
    6. child.style.left = child.resolvedStyle.left + panSpeed.x;
    7. child.style.top = child.resolvedStyle.top + panSpeed.y;

    If I run this enough times, the child will gradually drift away from its original position. This is all happening within the context of a scheduled operation:
    Code (CSharp):
    1.             m_PanSchedule = schedule
    2.                 .Execute(<run the code here>)
    3.                 .Every(10)
    4.                 .StartingIn(10);
    Can anyone explain what I might be doing wrong?




    PS: For reference, this is what WorldScale() does (inside a VisualElement subclass)

    Code (CSharp):
    1.         public Vector2 WorldScale()
    2.         {
    3.             Matrix4x4 draggableWorldTransform = worldTransform;
    4.             return new(draggableWorldTransform.m00, draggableWorldTransform.m11);
    5.         }