效果请看博主视频
if(Input.GetMouseButtonDown(0))
{
lineRenderer.positionCount = 0;
Vector2 outpos;
bool flag = RectTransformUtility.ScreenPointToLocalPointInRectangle(Minimap.rectTransform, Input.mousePosition, null, out outpos);
if (flag)
{
//这里采用点击小地图 在大地图中映射路径
//300 是小地图的 宽高 150是大地图的宽高
float x = outpos.x / 300f * 150f;
float z = outpos.y / 300f * 150f;
v3 = RayPos(new Vector3(x, 40, z));
// Debug.Log(v3 + "V3");
transform.LookAt(v3);
ai.SetDestination(v3);
allv3.Clear();
// Debug.Log(ai.path.corners.Length + "导航拐点数");
if (ai.path.corners.Length > 0)
{
// 这里不用 Incoke 的话 路径会延迟一次生成 可能是官方bug
Invoke("SetLine", 0.1f);
}
//如 路径有问题 补充else 更改拐点判断(1)
}
else
{
// Debug.Log("失败");
}
}
//可能是因为导航烘焙是 动态烘焙 所以用不了 ai.remainingDistance
if (Vector3.Distance(transform.position,v3)<=0.1f)
{
IsMove=false;
}
}
void SetLine()
{
Vector3[] arrV3 = ai.path.corners;
for (int i = 0; i < arrV3.Length; i++)
{
//这里做特殊处理
if( i == arrV3.Length - 1)
{
allv3.Add((arrV3[i]));
}
else
{
Vector3 dir = (arrV3[i + 1] - arrV3[i]).normalized;
//四舍五入取整
int dis = Mathf.RoundToInt(Vector3.Distance(arrV3[i + 1], arrV3[i]));
if (dis > 1.0f)
{
for (int j = 1; j <= dis; j++)
{
Vector3 pos = arrV3[i]+dir * j;
allv3.Add(RayPos(pos));
}
}
else
{
// allv3.Add(RayPos(arrV3[i]));
Debug.Log("测试不做处理");
}
}
}
// Debug.Log(allv3[allv3.Count - 1] + "终点信息1");
lineRenderer.positionCount=allv3.Count;
lineRenderer.SetPositions( allv3.ToArray());
IsMove = true;
}
//如 路径有问题 展开此方法(2)
void SetLineT()
{
}
public Vector3 RayPos(Vector3 pos) {
Vector3 newpos=new Vector3(pos.x,40,pos.z);
RaycastHit hit;
if(Physics.Raycast(new Ray(newpos,Vector3.down),out hit))
{
return hit.point;
}
Debug.Log("射线未检测到");
return Vector3.zero;
}
private void LateUpdate()
{
if (IsMove)
{
if (allv3.Count > 0)
{
//这里采用了双重保障
//可以只用点乘判断 不能只用位置判断
float dis = Vector3.Distance(transform.position, allv3[0]);
float dot = Vector3.Dot(transform.forward, allv3[0] - transform.position);
if (dis <= 0.2f || dot < 0)
{
allv3.Remove(allv3[0]);
lineRenderer.positionCount = allv3.Count;
lineRenderer.SetPositions(allv3.ToArray());
}
}
}
}