66 lines
2.2 KiB
C#
66 lines
2.2 KiB
C#
|
|
using System.Collections;
|
|||
|
|
using System.Collections.Generic;
|
|||
|
|
using UnityEngine;
|
|||
|
|
|
|||
|
|
public class SlideInPanelUI : MonoBehaviour
|
|||
|
|
{
|
|||
|
|
public AnimationCurve curve = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 1)); // 动画曲线
|
|||
|
|
private RectTransform rectTransform; // 目标面板的 RectTransform
|
|||
|
|
public float animationTime = 2f; // 动画持续时间
|
|||
|
|
public bool isFromLeft = true; // 是否从左侧移动进来,false 则从右侧移动进来
|
|||
|
|
public float offscreenDistance = 1.2f; // UI 元素开始时在屏幕外的距离比例,1表示完全在画布外,>1可以让其更远
|
|||
|
|
|
|||
|
|
private Vector3 startPos; // 动画开始位置
|
|||
|
|
private Vector3 endPos; // 动画结束位置
|
|||
|
|
private Vector3 ChuShi;
|
|||
|
|
|
|||
|
|
void Awake()
|
|||
|
|
{
|
|||
|
|
ChuShi = GetComponent<RectTransform>().localPosition;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
void OnEnable()
|
|||
|
|
{
|
|||
|
|
rectTransform = GetComponent<RectTransform>();
|
|||
|
|
rectTransform.localPosition = ChuShi;
|
|||
|
|
// 获取 Canvas 的宽度和高度
|
|||
|
|
float canvasWidth = rectTransform.rect.width;
|
|||
|
|
|
|||
|
|
// 根据比例设置初始位置
|
|||
|
|
if (isFromLeft)
|
|||
|
|
{
|
|||
|
|
startPos = new Vector3(-canvasWidth * offscreenDistance, rectTransform.localPosition.y, rectTransform.localPosition.z); // 屏幕左外侧
|
|||
|
|
}
|
|||
|
|
else
|
|||
|
|
{
|
|||
|
|
startPos = new Vector3(canvasWidth * offscreenDistance, rectTransform.localPosition.y, rectTransform.localPosition.z); // 屏幕右外侧
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
endPos = rectTransform.localPosition; // 最终位置为当前面板位置
|
|||
|
|
rectTransform.localPosition = startPos; // 初始位置设置为外部
|
|||
|
|
|
|||
|
|
// 启动动画
|
|||
|
|
StartCoroutine(SlideIn());
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
IEnumerator SlideIn()
|
|||
|
|
{
|
|||
|
|
float time = 0f;
|
|||
|
|
|
|||
|
|
while (time < animationTime)
|
|||
|
|
{
|
|||
|
|
// 计算动画的插值,归一化时间
|
|||
|
|
time += Time.deltaTime*2f;
|
|||
|
|
float t = time / animationTime;
|
|||
|
|
|
|||
|
|
// 根据动画曲线计算当前位置
|
|||
|
|
rectTransform.localPosition = Vector3.Lerp(startPos, endPos, curve.Evaluate(t));
|
|||
|
|
|
|||
|
|
yield return null;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 最终确保位置准确
|
|||
|
|
rectTransform.localPosition = endPos;
|
|||
|
|
}
|
|||
|
|
}
|