using System.Collections; using System.Collections.Generic; using UnityEngine; public class Test123 : MonoBehaviour { //进度 public Transform ToggleGroup; //开始消失的位置,重新出现的位置(即左右两端临界点) public Vector2 startPos, endPos; //移动的value值 private float value; //每个子物体的位置坐标(长度为子物体总量) Vector2[] vc = new Vector2[4]; //是否开始移动 bool Move; void Start() { } void Update() { //按下键盘左箭头(向左移动) if (Input.GetKeyDown(KeyCode.LeftArrow)) { //确保上次移动完成 if (value == 0) { for (int i = 0; i < transform.childCount; i++) { //记录下所有当前子物体的起始位置 vc[i] = transform.GetChild(i).localPosition; } Move = true; StartCoroutine(MoveL());//开启协程 } } //按下键盘右箭头(向右移动) if (Input.GetKeyDown(KeyCode.RightArrow)) { if (value == 0) { for (int i = 0; i < transform.childCount; i++) { vc[i] = transform.GetChild(i).localPosition; } Move = true; StartCoroutine(MoveR()); } } } IEnumerator MoveL() { while (Move) { yield return new WaitForEndOfFrame(); for (int i = 0; i < transform.childCount; i++) { //移动完成(value > 1)后,初始化value,开始判断 if (value > 1) { value = 0; //第一个子物体超过左边临界点 if (transform.GetChild(0).localPosition.x <= endPos.x) { //回到最右边 transform.GetChild(0).localPosition = new Vector2(startPos.x, transform.GetChild(0).localPosition.y); //把它变成子物体中的最后一个 transform.GetChild(0).SetAsLastSibling(); //显示当前进度 ToggleGroup.GetChild(transform.childCount - 1).SetAsFirstSibling(); } Move = false;//关闭循环 break;//在此处中断,下面代码不再执行 } //移动进程(可自己调整轮播快慢) value += Time.deltaTime * 0.5f; //new Vector2(vc[i].x - 1440, 0):在当前初始位置上向左移动1440 transform.GetChild(i).localPosition = Vector2.Lerp(vc[i], new Vector2(vc[i].x - 1440, 0), value); //其他的保持小图片,中间两个变换大小(根据实际情况) transform.GetChild(0).localScale = 0.8f * Vector2.one; transform.GetChild(1).localScale = Vector2.Lerp(Vector2.one, 0.8f * Vector2.one, value); transform.GetChild(2).localScale = Vector2.Lerp(Vector2.one, Vector2.one, value); transform.GetChild(3).localScale = 0.8f * Vector2.one; } } } /// /// 向右移动 /// /// IEnumerator MoveR() { while (Move) { yield return new WaitForEndOfFrame(); for (int i = 0; i < transform.childCount; i++) { if (value > 1) { value = 0; if (transform.GetChild(transform.childCount-1).localPosition.x >= startPos.x) { //回到最左边 transform.GetChild(transform.childCount - 1).localPosition = new Vector2(endPos.x, transform.GetChild(3).localPosition.y); //把它变成子物体中的第一个 transform.GetChild(transform.childCount - 1).SetAsFirstSibling(); //显示当前进度 ToggleGroup.GetChild(0).SetAsLastSibling(); } Move = false; break; } value += Time.deltaTime * 0.5f; //new Vector2(vc[i].x + 1440, 0):在当前初始位置上向右移动1440 transform.GetChild(i).localPosition = Vector2.Lerp(vc[i], new Vector2(vc[i].x + 1440, 0), value); transform.GetChild(0).localScale = Vector2.Lerp(Vector2.one, Vector2.one, value); transform.GetChild(1).localScale = Vector2.Lerp(Vector2.one, 0.8f * Vector2.one, value); transform.GetChild(2).localScale = 0.8f * Vector2.one; transform.GetChild(3).localScale = 0.8f * Vector2.one; } } } }