NG_/Assets/Scripts/UI/动画/SlideInPanel1UI.cs
2024-12-13 19:40:05 +08:00

63 lines
2.3 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SlideInPanel1UI : MonoBehaviour
{
public AnimationCurve curve = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 1)); // 动画曲线
private RectTransform rectTransform; // 目标面板的 RectTransform
public float animationTime = 0.5f; // 更短的动画持续时间
public bool isFromTop = true; // 是否从上方移动进来false 则从下方移动进来
public float offscreenDistance = 1.2f; // UI 元素开始时在屏幕外的距离比例1表示完全在画布外>1可以让其更远
private Vector3 startPos; // 动画开始位置
private Vector3 endPos; // 动画结束位置
void Start()
{
rectTransform = GetComponent<RectTransform>();
// 获取 Canvas 的高度
float canvasHeight = rectTransform.rect.height;
// 根据比例设置初始位置
if (isFromTop)
{
startPos = new Vector3(rectTransform.localPosition.x, canvasHeight * offscreenDistance, rectTransform.localPosition.z); // 屏幕上外侧
}
else
{
startPos = new Vector3(rectTransform.localPosition.x, -canvasHeight * offscreenDistance, rectTransform.localPosition.z); // 屏幕下外侧
}
endPos = rectTransform.localPosition; // 最终位置为当前面板位置
rectTransform.localPosition = startPos; // 初始位置设置为外部
// 启动动画
StartCoroutine(SlideIn());
}
IEnumerator SlideIn()
{
float time = 0f;
// 加速动画,时间增速(比如通过乘一个常数系数来加快时间流逝)
while (time < animationTime)
{
// 计算动画的插值,归一化时间
time += Time.deltaTime * 2f; // 增加 `2f` 的加速系数,使动画更快
// 确保 `time` 不超过 `animationTime`
time = Mathf.Min(time, animationTime);
// 根据动画曲线计算当前位置
rectTransform.localPosition = Vector3.Lerp(startPos, endPos, curve.Evaluate(time / animationTime));
yield return null;
}
// 最终确保位置准确
rectTransform.localPosition = endPos;
}
}