using System.Collections; using System.Collections.Generic; using UnityEngine; public class ScrollCamera : MonoBehaviour { public RectTransform scrollableImage; // 引用你的图片 private Vector3 targetPosition; private bool isScrolling = false; public Vector3 PlayerPos; // 添加Animation组件引用 public Animation characterAnimation; // 角色动画组件 public Transform player; public float proportion = 1; /// /// 最小值 /// public float minX; /// /// 最大值 /// public float maxX; /// /// 卷轴1 /// public RectTransform Scroll1; /// /// 卷轴2 /// public RectTransform Scroll2; void Start() { PlayerPos = new Vector3(Screen.width / 2, 0, 0); proportion = 375f / Screen.width; targetPosition = scrollableImage.localPosition; // 初始化目标位置为当前图片位置 if (Scroll1.gameObject.activeSelf) DebugScrollWidth(Scroll1); if (Scroll2.gameObject.activeSelf) DebugScrollWidth(Scroll2); } void DebugScrollWidth(RectTransform scroll) { if (scroll != null) { float width = scroll.rect.width; //Debug.Log($"UI元素 {scroll.name} 的宽度是: {width}"); minX = 0 - (width / 2) + Screen.width / 2 + 5; maxX = width / 2 - Screen.width / 2 - 5; } else { Debug.LogWarning($"UI元素 未正确赋值"); } } void Update() { if (Input.GetMouseButtonDown(0)) // 如果鼠标点击(或触摸屏上的点击){ { // 获取鼠标点击的屏幕坐标 Vector3 mousePosition = Input.mousePosition; //Debug.Log("点击位置: " + mousePosition); Vector3 offset = (mousePosition - PlayerPos) * proportion; //Debug.Log("插值: " + offset); if (offset.x > 0) { //Debug.Log("向右滑动"); player.transform.eulerAngles = new Vector3(0, -90, 0); } else { //Debug.Log("向左滑动"); player.transform.eulerAngles = new Vector3(0, 90, 0); } Vector3 newScrollableImagePos = new Vector3(scrollableImage.localPosition.x - offset.x, scrollableImage.localPosition.y, scrollableImage.localPosition.z); //Debug.Log("newScrollableImagePos: " + newScrollableImagePos); // 设置新的目标位置,只改变X轴 targetPosition = newScrollableImagePos; if (characterAnimation != null) { characterAnimation.Play("Running"); //Debug.Log("开始播放跑步动画 Running"); } // 开始滚动 isScrolling = true; } // 如果正在滚动 if (isScrolling) { // 计算新的位置 float step = 100 * Time.deltaTime; // 每秒移动100像素,你可以根据需要调整这个值 // 限定x轴的位置范围 Vector3 newPosition = Vector3.MoveTowards(scrollableImage.localPosition, targetPosition, step); // 限定x轴的位置范围 newPosition.x = Mathf.Clamp(newPosition.x, minX, maxX); scrollableImage.localPosition = newPosition; // 播放跑步动画 // 如果已经到达目标位置,停止滚动 if (scrollableImage.localPosition == targetPosition || scrollableImage.localPosition.x >= maxX || scrollableImage.localPosition.x <= minX) { isScrolling = false; // 强制停止所有动画,避免动画状态混乱 if (characterAnimation != null) { characterAnimation.Stop(); // 停止所有动画 // Debug.Log("已到达目的地,停止所有动画"); // 播放Stand动画 if (characterAnimation.GetClip("Stand") != null) { characterAnimation.Play("Stand"); player.transform.eulerAngles = new Vector3(0, 0, 0); // Debug.Log("开始播放Stand动画"); } else { //Debug.LogWarning("未找到Stand动画片段,请确保动画组件中有名为'Stand'的动画"); } } } } } }