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

时间:2017-06-15 10:04:08

标签: unity3d scrollview unity5 scaling

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);

1 个答案:

答案 0 :(得分:1)

Stack Overflow不是脚本服务:下次请尝试发布您已经尝试过的内容。

无论如何你可以这样做:

  • 获取UI元素到ScrollView中心的距离(仅当您的跑步机是水平时,在 x 轴上;如果是垂直的,则在 y 轴上)
  • 将此值除以画布宽度的一半
  • 获取结果的绝对值
  • 您现在的值介于0到1之间(1表示元素位于画布中间,0表示两侧)

快速实现这一点将是:

[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;
    }
}

请注意我添加了AnimationCurve属性,以便能够轻松控制缩放效果:曲线应从[0:1]开始,以[1:0]结束,如下所示:

Animation curve to control the scaling effect.

希望这有帮助,