Search Unity

Unity UI Positioning UI object according to it's child inside screen space

Discussion in 'UGUI & TextMesh Pro' started by 11tomi12, Jan 31, 2019.

  1. 11tomi12

    11tomi12

    Joined:
    Feb 25, 2016
    Posts:
    17
    I am implementing a speech bubble in my 2D game that positions itself over a character speaking. I would like it to stay within the screen space and implemented a function for this as shown below.
    It does work to some degree but I am struggling with calculating the position of the Main object according to the boundaries of the child speech bubble object. The structure is as following:

    Canvas
    Main speech bubble Rectangle (that needs to be moved)
    Bubble arrow (doesn't resize with text)
    Bubble Rectangle(has bubble image and resizes according to text, used for out of camera check)
    Text


    And the code:

    Code (CSharp):
    1. void CheckSetMenuInScreenSpace()
    2.     {
    3. //min is left bottom of screen, max upper right corner
    4.         var screenMin = new Vector2(0, 0);
    5.         var screenMax = (Vector2)new Vector3(Screen.width, Screen.height, 0);
    6.  
    7. //tried with this, didn't work
    8.         Vector3[] corners = new Vector3[4];
    9.         bubbleRect.GetWorldCorners(corners);
    10. //calculating boundaries (bottom left and top right) of the bubble RectTransform. not sure if I used pivot correctly in the formula
    11.         var bubbleRectMin = new Vector2(bubbleRect.transform.position.x - (bubbleRect.rect.width * bubbleRect.pivot.x), bubbleRect.transform.position.y - (bubbleRect.rect.height * bubbleRect.pivot.y));
    12.         var bubbleRectMax = new Vector2(bubbleRect.transform.position.x + (bubbleRect.rect.width * bubbleRect.pivot.x), bubbleRect.transform.position.y + (bubbleRect.rect.height * bubbleRect.pivot.y));
    13.  
    14.         if (bubbleRectMin.x < screenMin.x)
    15.         {
    16.             parentRect.anchoredPosition = new Vector2(screenMin.x + (bubbleRect.rect.width / 2), parentRect.anchoredPosition.y);
    17.  
    18.             var a = parentRect.rect.position;
    19.         }
    20.         else if (bubbleRectMax.x > screenMax.x)
    21.         {
    22.             parentRect.anchoredPosition = new Vector2(screenMax.x - (bubbleRect.rect.width / 2), parentRect.anchoredPosition.y);
    23.         }
    24.  
    25.         if (bubbleRectMin.y < screenMin.y)
    26.         {
    27.             parentRect.anchoredPosition = new Vector2(parentRect.anchoredPosition.x, screenMin.y + (bubbleRect.rect.height / 2));
    28.         }
    29.         else if (bubbleRectMax.y > screenMax.y)
    30.         {
    31.             parentRect.anchoredPosition = new Vector2(parentRect.anchoredPosition.x, screenMax.y - (bubbleRect.rect.height / 2));
    32.         }
    33.     }
    I think my problem is that I misunderstand screen space, transform.position and anchored position.