unity如何让人物按照指定路线行走(目标点方式)

在unity游戏开发中如何使物体按照指定的路线运动呢?代码如下,这里是寻找目标点的方式,如果目标点多的话请参照我上一篇博客的方法;

在unity场景中添加一个空物体path 然后在检查器中添加组件CinemachineSmoothPath,然后在WayPoints添加坐标点  Looped的意思是是否闭合路线,如果你需要闭合路线那就勾选上,我这里项目需求是不闭合

 

 然后新建一个脚本LoopPath

代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class LoopPath1 : MonoBehaviour
{
public GameObject gameObject;
public Button[] buttons;

public GameObject[] gos; //获取每个目标点,,注意数组顺序不能乱
public float speed = 3; //用于控制移动速度
int i = 0; //用于记录是第几个目标点
float des; //用于存储与目标点的距离

// Update is called once per frame
void Update()
{
//看向目标点
this.transform.LookAt(gos[i].transform);
//计算与目标点间的距离
des = Vector3.Distance(this.transform.position, gos[i].transform.position);
//Debug.Log(Input.text);
////移向目标
transform.position = Vector3.MoveTowards(this.transform.position, gos[i].transform.position, Time.deltaTime * speed);
int x = 1;
//如果移动到当前目标点,就移动向下个目标
if (des < 0.1f && i < gos.Length - 1)
{
i++;
}
}


}

posted @ 2022-05-31 17:10  嘿,阿然  阅读(3160)  评论(0编辑  收藏  举报