您当前的位置: 首页 >  unity

云小川

暂无认证

  • 4浏览

    0关注

    78博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

unity scrollview滚动到指定的位置

云小川 发布时间:2022-07-19 18:58:08 ,浏览量:4

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

public class ScrollViewNevigation : MonoSingleton
{

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

	// Use this for initialization
	void Start ()
	{

	    Init();
	    //Nevigate(content.GetChild(45).GetComponent());

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

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

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

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

    public void Nevigate(RectTransform item)
    {

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

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

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

        newNormalizedPosition = scrollRect.GetComponent().normalizedPosition - newNormalizedPosition;

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

        DOTween.To(() => scrollRect.GetComponent().normalizedPosition, x => scrollRect.GetComponent().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 上

  • 调用其中方法Nevigate()即可

    void Nevigate(RectTransform item)

    例如:Nevigate(content.GetChild(45).GetComponent());

  • 在脚本中,为了实现平滑移动而定位的效果,使用了DoTween插件

  • 原作者码云地址:Unity-ScrollViewNevigation: Unity3D使用ScrollView时,实现滑动定位到指定位置 - Gitee.com

关注
打赏
1663746399
查看更多评论
立即登录/注册

微信扫码登录

0.0375s