using UnityEngine; using UnityEngine.UI; using System.Collections; /// /// 单点 /// public class ScrollViewHorizontalClickMove : MonoBehaviour { ScrollRect scrollRect; // 引用ScrollRect组件 public float smoothTime = 0.3f; // 平滑过渡的时间 public float stepDistance = 0.16f; // 移动的距离 private float targetPosition; // 目标滚动位置 private bool isScrolling = false; // 是否正在滚动 private void Start() { scrollRect = GetComponent(); } public void ScrollLeft() { StartCoroutine(SmoothScroll(-stepDistance)); // 假设每次点击向左滚动一小部分 } public void ScrollRight() { StartCoroutine(SmoothScroll(stepDistance)); // 假设每次点击向右滚动一小部分 } private IEnumerator SmoothScroll(float direction) { if (isScrolling) yield break; // 如果已经在滚动,则不开始新的滚动 isScrolling = true; float elapsedTime = 0f; float lerp = 0f; // 计算开始时的当前位置和目标位置 float startPosition = scrollRect.horizontalNormalizedPosition; targetPosition = Mathf.Clamp(startPosition + direction, 0f, 1f); // 确保目标位置在有效范围内 // 循环直到达到目标位置或超过平滑时间 while (lerp < 1f && elapsedTime < smoothTime) { elapsedTime += Time.deltaTime; lerp = Mathf.SmoothStep(0f, 1f, elapsedTime / smoothTime); // 使用SmoothStep函数进行平滑插值 // 根据插值计算新的滚动位置 float newPosition = Mathf.Lerp(startPosition, targetPosition, lerp); scrollRect.horizontalNormalizedPosition = newPosition; // 等待下一帧 yield return null; } // 确保最终位置与目标位置一致 scrollRect.horizontalNormalizedPosition = targetPosition; isScrolling = false; } }