Hyluss

[Unity] Scroll rect normalizedPos to selected object center

May 22nd, 2019
592
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.46 KB | None | 0 0
  1.    public void CenterOnItem(RectTransform target)
  2.     {
  3.         //this is the center point of the visible area
  4.         var maskHalfSize = MaskTransform.rect.size * 0.5f;
  5.         var contentSize = _content.rect.size;
  6.         //get object position inside content
  7.         var targetRelativePosition =
  8.             _content.InverseTransformPoint(target.position);
  9.         //adjust for item size
  10.         targetRelativePosition += new Vector3(target.rect.size.x, target.rect.size.y, 0f) * 0.25f;
  11.         //get the normalized position inside content
  12.         var normalizedPosition = new Vector2(
  13.             Mathf.Clamp01(targetRelativePosition.x / (contentSize.x - maskHalfSize.x)),
  14.             1f - Mathf.Clamp01(targetRelativePosition.y / -(contentSize.y - maskHalfSize.y))
  15.             );
  16.         //we want the position to be at the middle of the visible area
  17.         //so get the normalized center offset based on the visible area width and height
  18.         var normalizedOffsetPosition = new Vector2(maskHalfSize.x / contentSize.x, maskHalfSize.y / contentSize.y);
  19.         //and apply it
  20.         normalizedPosition.x -= (1f - normalizedPosition.x) * normalizedOffsetPosition.x;
  21.         normalizedPosition.y += normalizedPosition.y * normalizedOffsetPosition.y;
  22.  
  23.         normalizedPosition.x = Mathf.Clamp01(normalizedPosition.x);
  24.         normalizedPosition.y = Mathf.Clamp01(normalizedPosition.y);
  25.  
  26.         scroll.normalizedPosition = normalizedPosition;
  27.        
  28.     }
Advertisement
Comments
  • User was banned
Add Comment
Please, Sign In to add comment