unity scrollview滚动到指定的位置

using UnityEngine;
using DG.Tweening;
using UnityEngine.UI;

public class ScrollViewNevigation : MonoSingleton<ScrollViewNevigation>
{

    private ScrollRect scrollRect;
    private RectTransform viewport;
    private RectTransform content;

	// Use this for initialization
	void Start ()
	{

	    Init();
	    //Nevigate(content.GetChild(45).GetComponent<RectTransform>());

	}
	
	// Update is called once per frame
	void Update () {
	
	}

    private void Init()
    {
        if (scrollRect == null)
        {
            scrollRect = this.GetComponent<ScrollRect>();
        }

        if (viewport == null)
        {
            viewport = this.transform.Find("Viewport").GetComponent<RectTransform>();
        }

        if (content == null)
        {
            content = this.transform.Find("Viewport/Content").GetComponent<RectTransform>();
        }
    }

    public void Nevigate(RectTransform item)
    {

        Vector3 itemCurrentLocalPostion = scrollRect.GetComponent<RectTransform>().InverseTransformVector(ConvertLocalPosToWorldPos(item));
        Vector3 itemTargetLocalPos = scrollRect.GetComponent<RectTransform>().InverseTransformVector(ConvertLocalPosToWorldPos(viewport));

        Vector3 diff = itemTargetLocalPos - itemCurrentLocalPostion;
        diff.z = 0.0f;

        var newNormalizedPosition = new Vector2(
            diff.x / (content.GetComponent<RectTransform>().rect.width - viewport.rect.width),
            diff.y / (content.GetComponent<RectTransform>().rect.height - viewport.rect.height)
            );

        newNormalizedPosition = scrollRect.GetComponent<ScrollRect>().normalizedPosition - newNormalizedPosition;

        newNormalizedPosition.x = Mathf.Clamp01(newNormalizedPosition.x);
        newNormalizedPosition.y = Mathf.Clamp01(newNormalizedPosition.y);

        DOTween.To(() => scrollRect.GetComponent<ScrollRect>().normalizedPosition, x => scrollRect.GetComponent<ScrollRect>().normalizedPosition = x, newNormalizedPosition, 0.8f);
    }

    private Vector3 ConvertLocalPosToWorldPos(RectTransform target)
    {
        var pivotOffset = new Vector3(
            (0.5f - target.pivot.x) * target.rect.size.x,
            (0.5f - target.pivot.y) * target.rect.size.y,
            0f);

        var localPosition = target.localPosition + pivotOffset;

        return target.parent.TransformPoint(localPosition);
    }
}

简介

1.在Unity3D中,使用ScrollView时,

经常需要让游戏在运行时,将ScrollView定位到某一指定Item上。

比如:进入游戏后,在关卡界面大地图推图指当前关卡等。

脚本ScrollViewNevigation.cs 则可以实现此功能

2. 使用说明

  • 请尽量保证ScrollView组件层级及命名如下,为减少使用者拖拽工作量,在代码中已根据层级和命名初始化完毕

  • 将脚本ScrollViewNevigation.cs 挂在 ScrollView 上

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值