Unity3d-路径巡逻

使用U3D实现的简单巡逻方法

  • 游戏对象逐个向组成路径的节点进行直线移动
  • 两种巡逻方案
    1. 根据列表顺序移动,到达最后一个后,直接返回第一个,重新开始循环
    2. 根据列表顺序移动,到达最后一个后,根据顺序反向移动到第一个,重新开始循环

巡逻方案1

实现代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public Transform pathNodes;
public float moveSpeed = 5f; //移动速度

private int currentNodeIndex = 0;//当前节点位置的索引

void Start()
{
//初始位置
transform.position = pathNodes.GetChild(0).position;
}

void Update()
{
//检查是否到达
if (Vector3.Distance(transform.position, pathNodes.GetChild(currentNodeIndex).position) < 0.1f)
{
currentNodeIndex = (currentNodeIndex + 1) % pathNodes.childCount;
}

//方向
Vector3 targetDirection = pathNodes.GetChild(currentNodeIndex).position - transform.position;
targetDirection.Normalize();

//移动
transform.position += targetDirection * moveSpeed * Time.deltaTime;
transform.rotation = Quaternion.LookRotation(targetDirection);
}

实现思路

  1. 首先将对象初始化在起始位置
  2. 每帧检查对象是否到达节点,当对象与节点距离小于0.1则判断为到达
  3. 到达后将索引号+1,使用%运算让索引号在节点列表中循环
  4. 计算方向
  5. 旋转对象,朝节点移动

巡逻方案2

实现代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public Transform pathNodes;
public float moveSpeed = 5f; //移动速度

private int currentNodeIndex = 0;//当前节点位置的索引
private bool isMovingForward = true; //是否正向移动

void Start()
{
//初始位置
transform.position = pathNodes.GetChild(0).position;
}

void Update()
{
//检查是否到达
if (Vector3.Distance(transform.position, pathNodes.GetChild(currentNodeIndex).position) < 0.1f)
{
//方案1
//currentNodeIndex = (currentNodeIndex + 1) % pathNodes.childCount;

//方案2
if (isMovingForward)
{
currentNodeIndex++;
if (currentNodeIndex >= pathNodes.childCount)
{
currentNodeIndex = pathNodes.childCount - 2;
isMovingForward = false;
}
}
else
{
currentNodeIndex--;
if (currentNodeIndex < 0)
{
currentNodeIndex = 1;
isMovingForward = true;
}
}
}

//方向
Vector3 targetDirection = pathNodes.GetChild(currentNodeIndex).position - transform.position;
targetDirection.Normalize();

//移动
transform.position += targetDirection * moveSpeed * Time.deltaTime;
transform.rotation = Quaternion.LookRotation(targetDirection);

实现思路

  1. 首先将对象初始化在起始位置
  2. 每帧检查对象是否到达节点,当对象与节点距离小于0.1则判断为到达
  3. 添加一个变量记录正向及反向移动,正向时到达节点后将索引号+1,反向时到达节点后索引号-1
  4. 计算方向
  5. 旋转对象,朝节点移动