DaoNiaoShu_Dog/Assets/_Scripts/FrameworkYiLiao/Scroll/ScrollViewVerticalMoveItem.cs

36 lines
1.4 KiB
C#

using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class ScrollViewVerticalMoveItem : MonoBehaviour
{
public ScrollRect scrollRect; // 你需要将 ScrollRect 拖到这里
public float cellHeight = 100f; // 每个格子的高度,自己根据实际情况设置
public void MoveDown()
{
// 计算目标位置
float newY = scrollRect.content.anchoredPosition.y + cellHeight;
// 获取Content的高度和可视区域的高度
float contentHeight = scrollRect.content.sizeDelta.y;
float viewportHeight = scrollRect.viewport.rect.height;
// 确保不超过最大 Y 值
newY = Mathf.Min(newY, contentHeight - viewportHeight);
// Smoothly move to the new position
StartCoroutine(SmoothMove(scrollRect.content.anchoredPosition.y, newY));
}
private IEnumerator SmoothMove(float startY, float targetY)
{
float elapsedTime = 0.0f;
float duration = 0.3f; // 移动持续时间
while (elapsedTime < duration)
{
float newY = Mathf.Lerp(startY, targetY, (elapsedTime / duration));
scrollRect.content.anchoredPosition = new Vector2(scrollRect.content.anchoredPosition.x, newY);
elapsedTime += Time.deltaTime;
yield return null;
}
// 确保最后位置准确
scrollRect.content.anchoredPosition = new Vector2(scrollRect.content.anchoredPosition.x, targetY);
}
}