我在尝试在Unity中创建一个AI敌人。我正在编写AI移动的代码。AI应该从一个起点开始,然后移动到某个点后返回,但我的代码不知为何不起作用。
代码如下:
using System.Collections;using System.Collections.Generic;using UnityEngine;public class EnemyMoveAround : MonoBehaviour{ public Vector3 start; public Vector3 startOrientation; public Vector3 end; public int speed; public int moveMode; // Start is called before the first frame update void Start() { transform.position = start; transform.localScale = startOrientation; } // Update is called once per frame void Update() { transform.position += new Vector3(startOrientation * speed, 0); if (transform.position > end || transform.postion < start) { startOrientation = startOrientation * -1; } }}
回答:
你可以使用Unity内置的NavMesh系统
基本操作是检查终点位置与当前位置之间的距离
然后你可以将NavMeshAgent的目标设置为终点位置,例如:(你命名的变量).SetDestination(end);
当终点位置与当前位置之间的距离变小时,你可以将目标切换到起始位置,并将一个布尔值如isReturning设置为true。
如果你觉得我的回答不够清楚,可以在YouTube上观看NavMesh的教程
希望这对你有帮助!