64 lines
2.3 KiB
C#
64 lines
2.3 KiB
C#
using UnityEngine;
|
||
using DG.Tweening;
|
||
|
||
public class SnowHpControl : MonoBehaviour
|
||
{
|
||
public Vector3 minScale = new Vector3(0f, 0.1f, 1f); // 最小缩放
|
||
public Vector3 maxScale = new Vector3(1f, 0.1f, 1f); // 最大缩放
|
||
public float duration = 1f; // 从min到max的时间
|
||
public float moveSpeed = 0.005f; // 向上飘动的速度
|
||
public float fadeDuration = 0f; // 消失时间(设置为零实现即时消失)
|
||
public float moveDistance = 2f; // 向上飘动的最大距离
|
||
public Canvas targetCanvas; // 目标画布,用于确保UI元素在该画布上移动
|
||
|
||
private Renderer rend; // 用于获取物体的Renderer来控制透明度
|
||
private Vector3 initialPosition;
|
||
|
||
void Start()
|
||
{
|
||
targetCanvas = transform.parent.GetComponent<Canvas>();
|
||
|
||
// 获取Renderer
|
||
rend = GetComponent<Renderer>();
|
||
|
||
// 确保血条的初始化位置在目标画布的正确位置上
|
||
if (targetCanvas.renderMode == RenderMode.WorldSpace)
|
||
{
|
||
// 如果目标画布是WorldSpace模式,使用世界坐标
|
||
initialPosition = transform.position;
|
||
}
|
||
else
|
||
{
|
||
// 如果是ScreenSpace模式,我们需要转化屏幕坐标到世界坐标
|
||
initialPosition = targetCanvas.worldCamera.ScreenToWorldPoint(transform.position);
|
||
}
|
||
|
||
// 初始化血条的缩放
|
||
transform.localScale = minScale;
|
||
|
||
// 使用DOTween做缩放动画,从最小缩放到最大缩放
|
||
transform.DOScale(maxScale, duration).SetEase(Ease.InOutQuad).OnComplete(StartFading);
|
||
|
||
// 启动血条向上飘动的动画(从初始位置向上移动 `moveDistance` 单位)
|
||
transform.DOMoveY(initialPosition.y + moveDistance, duration).SetEase(Ease.InOutQuad);
|
||
}
|
||
|
||
private void StartFading()
|
||
{
|
||
// 如果fadeDuration为零,直接销毁
|
||
if (fadeDuration == 0f)
|
||
{
|
||
Destroy(gameObject);
|
||
}
|
||
else
|
||
{
|
||
// 如果fadeDuration大于零,才使用DOTween
|
||
// 通过DOTween设置透明度渐变到零,动画完成后销毁对象
|
||
DOTween.ToAlpha(() => rend.material.color, x => rend.material.color = x, 0f, fadeDuration).OnComplete(() =>
|
||
{
|
||
Destroy(gameObject); // 动画完成后销毁对象
|
||
});
|
||
}
|
||
}
|
||
}
|