实现A星寻路的具体步骤

1.位场景中的障碍物和地面添加不同层级。

2.场景中添加一个空物体,并为空物体添加AStarPath脚本。

3.设置高度测试和碰撞测试参数。

4.为玩家添加Seeker脚本。

5.添加A*代码。如下:

//先有一条路
private Path path;
//开启寻路的组件
private Seeker seeker;
//目标点
public Transform target;
//更新路点,路点索引
private int currentWayPoint;
//到下一个路点的距离
public float nextWayPointDistance;
//移动旋转速度
public float moveSpeed;
public float rotateSpeed;
// Use this for initialization
void Start () {
seeker = GetComponent<Seeker>();
//获取组件
seeker.StartPath( this.transform.position , target.position,OnPathCompeleter );
//开启寻路
}

// Update is called once per frame
void Update () {
if ( path==null )
{
return;
}
if ( currentWayPoint>=path.vectorPath.Count )
{
return;
}
//移动,旋转
//获取移动方向
Vector3 dirction = ( path.vectorPath[currentWayPoint] -
transform.position ).normalized;
//获取速度
dirction = moveSpeed * dirction;
//移动
transform.Translate( dirction * Time.deltaTime,Space.World );
//旋转
Quaternion rotationTarget =
Quaternion.LookRotation( dirction );
transform.rotation = Quaternion.Lerp( transform.rotation ,
rotationTarget , rotateSpeed * Time.deltaTime );
//更新路点
if ( Vector3.Distance(transform.position,
path.vectorPath[currentWayPoint])<nextWayPointDistance )
{
currentWayPoint++;
return;
}
}
/// <summary>
/// 新的寻路开始之前被调用
/// </summary>
/// <param name="p"></param>
private void OnPathCompeleter(Path p)
{
if ( !p.error )
{
path = p;
print( "找到路了" );
currentWayPoint = 0;
}
}

猜你喜欢

转载自www.cnblogs.com/heipi-1799700431/p/9236679.html