using UnityEngine; using UnityEngine.UI; public class ImageMoveSX : MonoBehaviour { public Image targetImage; public float speed = 100f; public float topLimit = 200f; public float bottomLimit = -200f; private RectTransform rectTransform; private Vector3 initialPosition; private int direction = 1; void Start() { if (targetImage == null) { return; } rectTransform = targetImage.GetComponent(); initialPosition = rectTransform.anchoredPosition; } void Update() { if (targetImage == null) return; // 上下移动 rectTransform.anchoredPosition += new Vector2(0, direction * speed * Time.deltaTime); // 检查边界,反转方向 if (rectTransform.anchoredPosition.y > initialPosition.y + topLimit) { rectTransform.anchoredPosition = new Vector2(rectTransform.anchoredPosition.x, initialPosition.y + topLimit); direction = -1; // 向下 } else if (rectTransform.anchoredPosition.y < initialPosition.y + bottomLimit) { rectTransform.anchoredPosition = new Vector2(rectTransform.anchoredPosition.x, initialPosition.y + bottomLimit); direction = 1; // 向上 } } }