using UnityEngine; using DG.Tweening; using UnityEngine.UI; public class SnowHpControl : MonoBehaviour { public Vector3 minScale = new Vector3(0.5f, 0.5f, 1f); // 最小缩放 public Vector3 maxScale = new Vector3(1.5f, 1.5f, 1f); // 最大缩放 public float duration = 1f; // 动画的总持续时间 public float moveDistance = 5f; // 跳跃的水平距离 public float fadeDuration = 0.5f; // 消失时间 public Canvas targetCanvas; // 目标画布,用于确保UI元素在该画布上移动 public int direction;//显示方向 private Renderer rend; // 用于获取物体的Renderer来控制透明度 private Vector3 initialPosition; void Start() { } public void CreateText() { targetCanvas = transform.parent.GetComponent(); // 获取Renderer rend = GetComponent(); // 确保物体的初始位置在目标画布的正确位置上 if (targetCanvas.renderMode == RenderMode.WorldSpace) { // 如果目标画布是WorldSpace模式,使用世界坐标 initialPosition = transform.position; } else { // 如果是ScreenSpace模式,我们需要转化屏幕坐标到世界坐标 initialPosition = targetCanvas.worldCamera.ScreenToWorldPoint(transform.position); } // 随机初始化位置(在初始位置附近) float randomX; if (direction == 0) { randomX = Random.Range(moveDistance / 4f, moveDistance)+moveDistance/2; } else { randomX = Random.Range(-moveDistance, -moveDistance / 4f)-moveDistance/2; } float randomY = Random.Range(-moveDistance / 4f, 0); // 在Y轴上也加一点随机性 transform.position = initialPosition; // 随机初始化大小(在minScale和maxScale之间) float randomScaleX = Random.Range(minScale.x, maxScale.x); float randomScaleY = Random.Range(minScale.y, maxScale.y); transform.localScale = new Vector3(randomScaleX, randomScaleY, 1f); // 使用DOTween做跳跃动画 Sequence sequence = DOTween.Sequence(); // 1. 跳跃并逐渐变大 sequence.Append(transform.DOJump(new Vector3(initialPosition.x + randomX, initialPosition.y + randomY), 0.3f, 1, 0.5f) .SetEase(Ease.OutQuad) // 跳跃效果,使用OutQuad让跳跃过程中速度逐渐变慢 ); //sequence.Join(transform.DOMoveY(initialPosition.y -( randomY + moveDistance) / 2f, 0.6f) // .SetEase(Ease.OutQuad) // 跳跃的高度,跟X轴的跳跃配合 //); sequence.Join(transform.DOScale(maxScale, 0.5f) // 同时控制大小,从初始值到最大值 .SetEase(Ease.OutBack) // 使用OutBack让物体变大时有一个“弹跳”的效果 ); // 2. 动画完成后,逐渐变淡并销毁 sequence.Append(transform.DOScale(Vector3.zero, 0.5f).SetEase(Ease.Linear)); // 缩小效果,模拟消失的感觉 sequence.Append(transform.GetComponent().DOFade(0f, fadeDuration).OnComplete(() => { Destroy(gameObject); // 动画完成后销毁对象 })); } }