using UnityEngine; using DG.Tweening; using UnityEngine.UIElements; using System.Collections.Generic; // 引入DoTween命名空间 [System.Serializable] public class waypoints { public List _waypoints = new List(); } public class SimplePathfindingDoTween : Fun { public waypoints waypoints = new waypoints();// 预设的路径点 public float moveSpeed; // 控制移动速度的参数(更高值表示更快的速度) private int currentWaypointIndex = 0; // 当前路径点的索引 Vector3 Vector3 = new Vector3(); public Tween pathTween; public float speedFactor=1;//速度因子 [Header("旋转的动画")]public GameObject obj; public void MoveToNextWaypoint(GameObject gameObject, float moveSpeed) { if (currentWaypointIndex < waypoints._waypoints.Count) { // 获取目标路径点 Transform targetWaypoint = waypoints._waypoints[waypoints._waypoints.Count - 1]; // 计算路径点之间的距离 float distance = Vector3.Distance(gameObject.transform.position, targetWaypoint.position); // 根据设置的速度计算时间 float timeToReach = distance * 10 / moveSpeed; // 根据速度控制匀速移动的时间 // 获取路径的所有点 Vector3[] path = new Vector3[waypoints._waypoints.Count - currentWaypointIndex]; for (int i = 0; i < path.Length; i++) { path[i] = waypoints._waypoints[currentWaypointIndex + i].position; if (i!=0&&i!= path.Length-1) { // 在Y轴方向上做一定的随机改变,可以设置一个波动范围 path[i].y += Random.Range(-0.1f, 0.1f); // 修改 Y 值的波动范围 } } // 使用DoTween的DOPath来平滑地移动 pathTween=gameObject.transform.DOPath(path, timeToReach, PathType.Linear) .SetEase(Ease.Linear) .OnUpdate(() => { pathTween.timeScale = speedFactor; RotateTowardsTarget(); } ); // 每次更新时调整旋转 } else { Debug.Log("到达终点!"); } } public void PauseAnimation() { // 暂停动画 transform.DOPause(); } // 控制DoTween的速度,接受一个新的速度因子和一个恢复时间 public void ChangeSpeed(float newSpeedFactor, float restoreTime) { // 改变路径动画的速度因子 pathTween.timeScale = newSpeedFactor; // 设置一个延迟恢复原始速度的功能 DOTween.To(() => 0f, x => { }, 0f, restoreTime).OnKill(() => { Debug.Log("设置减速+++++++++++++++++"); // 在延迟结束后恢复原来的速度 pathTween.timeScale = 1f; // 恢复原速度 }); } public void StopPathDoTween(float stopTime)//暂停移动 { // 暂停当前的动画 pathTween.Pause(); // 插入一个自定义的延迟(僵直时间) DOTween.To(() => 0f, x => { }, 0f, stopTime).OnKill(() => { // 在延迟结束后恢复动画 pathTween.Play(); }); } void RotateTowardsTarget() { Vector3 _vector3 = Vector3 - gameObject.transform.position; Vector3 = gameObject.transform.position; if (_vector3.x>0) { // 物体在目标的右边或平行,设置物体的y旋转为180°,面向左侧 obj.transform.rotation = Quaternion.Euler(0, 0, 0); } else { // 物体在目标的左边,设置物体的y旋转为0°,面向右侧 obj.transform.rotation = Quaternion.Euler(0, 180, 0); } } }