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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Best algorithm to clamp a UI window within the canvas?

Discussion in 'UGUI & TextMesh Pro' started by StarManta, Mar 26, 2015.

  1. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,744
    Basically just what the title says. I'm having trouble developing a non-complicated algorithm for keeping a window (whose position is set in script, tracking objects in the scene) within the bounds of the canvas. Does anyone have a good algorithm for this?
     
    _TheFuture_ likes this.
  2. User340

    User340

    Joined:
    Feb 28, 2007
    Posts:
    3,001
    Wouldn't a simple check for if (transform.localPosition.x < 0) transform.localPosition.x = 0 work? Is there something specific about canvas that makes it tricky?
     
  3. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,744
    That only works on the anchoredPosition of the window, not all sides of the rectangle.
     
  4. Yukichu

    Yukichu

    Joined:
    Apr 2, 2013
    Posts:
    420
    The UIDragPanel ClampToWindow() from the tutorial project doesn't work?

    Code (csharp):
    1.     // Clamp panel to area of parent
    2.     void ClampToWindow()
    3.     {
    4.         Vector3 pos = panelRectTransform.localPosition;
    5.  
    6.         Vector3 minPosition = parentRectTransform.rect.min - panelRectTransform.rect.min;
    7.         Vector3 maxPosition = parentRectTransform.rect.max - panelRectTransform.rect.max;
    8.  
    9.         pos.x = Mathf.Clamp(panelRectTransform.localPosition.x, minPosition.x, maxPosition.x);
    10.         pos.y = Mathf.Clamp(panelRectTransform.localPosition.y, minPosition.y, maxPosition.y);
    11.  
    12.         panelRectTransform.localPosition = pos;
    13.     }
     
    Bamboy, GameDevMig, da183 and 9 others like this.
  5. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,744
    I always forget that these things have a 'rect' property.... That's the magic bit I was missing. Thanks :)