UnityCommon/Role/move/2D/SimplePathfindingDoTween.cs
2024-12-11 16:51:55 +08:00

66 lines
2.1 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;
using UnityEngine.UIElements;
using System.Collections.Generic; // 引入DoTween命名空间
[System.Serializable]
public class waypoints
{
public List<Transform> _waypoints = new List<Transform>();
}
public class SimplePathfindingDoTween : Fun
{
public waypoints waypoints = new waypoints();// 预设的路径点
public float moveSpeed = 1f; // 控制移动速度的参数(更高值表示更快的速度)
private int currentWaypointIndex = 0; // 当前路径点的索引
Vector3 Vector3 = new Vector3();
public void MoveToNextWaypoint(GameObject gameObject)
{
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; // 根据速度控制匀速移动的时间
// 使用DoTween的DOPath来平滑地移动到目标位置
Vector3[] path = new Vector3[waypoints._waypoints.Count - currentWaypointIndex];
for (int i = 0; i < path.Length; i++)
{
path[i] = waypoints._waypoints[currentWaypointIndex + i].position;
}
gameObject.transform.DOPath(path, timeToReach, PathType.Linear)
.SetEase(Ease.Linear).OnUpdate(() => RotateTowardsTarget()); // 每次更新时调整旋转
}
else
{
Debug.Log("到达终点!");
}
}
void RotateTowardsTarget()
{
Vector3 _vector3 = Vector3 - gameObject.transform.position;
Vector3 = gameObject.transform.position;
if (_vector3.x>0)
{
// 物体在目标的右边或平行设置物体的y旋转为180°面向左侧
gameObject.transform.rotation = Quaternion.Euler(0, 0, 0);
}
else
{
// 物体在目标的左边设置物体的y旋转为0°面向右侧
gameObject.transform.rotation = Quaternion.Euler(0, 180, 0);
}
}
}