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 上
-
调用其中方法
Nevigate()
即可void Nevigate(RectTransform item)
例如:
Nevigate(content.GetChild(45).GetComponent<RectTransform>());
-
在脚本中,为了实现平滑移动而定位的效果,使用了DoTween插件
-
原作者码云地址:Unity-ScrollViewNevigation: Unity3D使用ScrollView时,实现滑动定位到指定位置 - Gitee.com