本文主要是对该文章的改进:Unity学习笔记--易学易会的unity中A星寻路插件:A*Pathfind Project的使用_秋瞑小雁客的博客-CSDN博客_unity 寻路插件
上述文章中的代码在运行过程中,角色到达目标点后,会出现数组越界的情况
针对这个问题,我们定位在代码区的第51行
Vector3 dir = (path.vectorPath[currentWaypoint + 1] - transform.position);
我认为主要是 + 1 引起的数组越界
解决方法如下:
1.声明一个变量,作为判断使用
int flag = 1;
2.在45-49行的代码中加入 flag++
if (currentWaypoint >= path.vectorPath.Count)
{
Debug.Log("路径搜索结束");
flag++;
return;
}
3.对这些代码进行判断
修改后如下
if ((currentWaypoint + 1) <= flag)
{
Vector3 dir = (path.vectorPath[currentWaypoint + 1] - transform.position);//.normalized;
dir *= speed * Time.fixedDeltaTime;
//玩家转向
transform.Translate(Vector3.forward * Time.fixedDeltaTime * speed);
Quaternion targetRotation = Quaternion.LookRotation(dir);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * turnSpeed);//(起始方向,终止方向,速度)
//玩家当前位置与当前的航向点距离小于一个给定值后,转向下一个航向点
if (Vector3.Distance(transform.position, path.vectorPath[currentWaypoint]) < nextWaypointDistance)
{
currentWaypoint++;
return;
}
}
对此,成功解决数组越界问题
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)