Cute_demon_attacks/meng_yao/Assets/Prefabs/charatar/enemy/SnowHpControl.cs

82 lines
2.9 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; // 移动和缩放的持续时间
public float moveSpeed = 0.005f; // 向上飘动的速度
public float fadeDuration = 0f; // 消失时间(设置为零实现即时消失)
public float moveDistance = 1f; // 向上飘动的最大距离
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做移动和缩放动画移动过程中从minScale逐渐变大
Sequence sequence = DOTween.Sequence();
// 1. 先移动的过程中从minScale逐渐变大到maxScale
sequence.Append(transform.DOMoveY(initialPosition.y + moveDistance, 0.3f)
.SetEase(Ease.InOutQuad) // 移动动画
);
sequence.Join(transform.DOScale(maxScale, 0.3f)
.SetEase(Ease.InOutQuad) // 同步缩放动画从minScale到maxScale
);
// 2. 到达终点后物体放大比maxScale大
sequence.Append(transform.DOScale(maxScale * 1.5f, 0.3f)
.SetEase(Ease.OutBack) // 终点放大使用OutBack使得放大更明显
);
//// 3. 缩回到maxScale
//sequence.Append(transform.DOScale(maxScale, 0.3f)
// .SetEase(Ease.InOutQuad) // 缩回时使用InBack使得动画自然
//);
// 4. 动画完成后进行消失动画
sequence.OnComplete(() => StartFading());
}
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); // 动画完成后销毁对象
});
}
}
}