ImageMoveSX.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. public class ImageMoveSX : MonoBehaviour
  4. {
  5. public Image targetImage;
  6. public float speed = 100f;
  7. public float topLimit = 200f;
  8. public float bottomLimit = -200f;
  9. private RectTransform rectTransform;
  10. private Vector3 initialPosition;
  11. private int direction = 1;
  12. void Start()
  13. {
  14. if (targetImage == null)
  15. {
  16. return;
  17. }
  18. rectTransform = targetImage.GetComponent<RectTransform>();
  19. initialPosition = rectTransform.anchoredPosition;
  20. }
  21. void Update()
  22. {
  23. if (targetImage == null) return;
  24. // 上下移动
  25. rectTransform.anchoredPosition += new Vector2(0, direction * speed * Time.deltaTime);
  26. // 检查边界,反转方向
  27. if (rectTransform.anchoredPosition.y > initialPosition.y + topLimit)
  28. {
  29. rectTransform.anchoredPosition = new Vector2(rectTransform.anchoredPosition.x, initialPosition.y + topLimit);
  30. direction = -1; // 向下
  31. }
  32. else if (rectTransform.anchoredPosition.y < initialPosition.y + bottomLimit)
  33. {
  34. rectTransform.anchoredPosition = new Vector2(rectTransform.anchoredPosition.x, initialPosition.y + bottomLimit);
  35. direction = 1; // 向上
  36. }
  37. }
  38. }