Cute_demon_attacks/meng_yao/Assets/Prefabs/charatar/enemy/SnowHpControl.cs
wulongxiao b9db3ff518 add
2024-12-14 21:15:57 +08:00

64 lines
2.3 KiB
C#
Raw 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 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); // 动画完成后销毁对象
});
}
}
}