Search code examples
scrollviewunity-game-enginescaling

How to scale a object with distance from the center of the canvas in UNITY?


i need to achieve a treadmill effect for the scroll view, i.e while scrolling the center object need to reduce in scale when moving away from center and vice versa? can someone point me in the right direction, im already calculating the center of the scrollview from the elements to achieve the snapping effect.

*Solved by very cheap method might not be suitable for everyone the process is by getting the distance from the button/elements in the scrollview to the center and learping with the said distance with the amount of scale needed

istReposition = center.GetComponent<RectTransform>().position.x - bttn.GetComponent<RectTransform>().position.x;
distance = Mathf.Abs(distReposition);
Vector3 minscale = Vector3.one * maximundistanceScale;
Vector3 maxScale = Vector3.one * minimundistanceScale;
bttn[i].GetComponent<RectTransform>().localScale = Vector3.Lerp(maxScale,minscale, distance);

Solution

  • Stack Overflow isn't a scripting service: next time please try to post what you've already tried.

    Anyway you can do it like this:

    • Getting the distance from your UI element to the center of the ScrollView (on the x axis only if your treadmill is horizontal or on the y axis if it's vertical)
    • Dividing this value by half the width of the canvas
    • Getting the absolute value of the result
    • You now have a value ranging from 0 to 1 (1 being when the element is on the middle of the canvas and 0 on the sides)

    A quick implementation of this would be:

    [RequireComponent(typeof(RectTransform))]
    public class TestScript : MonoBehaviour
    {
        [SerializeField]
        private float m_CenterScale;
        [SerializeField]
        private float m_BorderScale;
        [SerializeField]
        private AnimationCurve m_ScalingCurve; // Must be from 1 to 0 on y axis and from 0 to 1 on x axis
    
        protected override void Update()
        {
            float scrollviewCenterPosition = GetComponentInParent<ScrollRect>().GetComponent<RectTransform>().position.x;
            float distanceFromCenter = transform.position.x - scrollviewCenterPosition ;
            float ratio = Mathf.Abs(distanceFromCenter / (GetComponentInParent<ScrollRect>().GetComponent<RectTransform>().rect.width * 0.5f));
            float scaleValue = m_BorderScale + (m_CenterScale - m_BorderScale) * m_ScalingCurve.Evaluate(ratio);
            (transform as RectTransform).localScale = Vector3.one * scaleValue;
        }
    }
    

    Please note I added an AnimationCurve property to be able to control the scaling effect easily: the curve should start at [0:1] and end at [1:0] like this:

    Animation curve to control the scaling effect.

    Hope this helps,