您好,我是 c# 和 unity 的新手,有人知道在玩家触发 AI 追逐玩家代码后如何让 AI 返回到预先定义的航路点吗?因为我一直在使用这个新代码并尝试使用 agent.setdestination 但它不断给我索引超出范围异常。有人知道怎么修这个东西吗。
public NavMeshAgent agent;
public Transform player;
public LayerMask whatIsGround, whatIsPlayer;
//Attacking
public float timeBetweenAttacks;
bool alreadyAttacked;
//States
public float sightRange, attackRange;
public bool playerInSightRange, playerInAttackRange;
public float MovementSpeed = 3f;
public float TurningSpeed = 3f;
Vector3 dist;
bool WpReached;
GameObject StartingPoint;
string TargetWpToGo;
private int CurrentWpNumber;
Rigidbody rb;
public Transform[] waypoints;
public int speed;
private int waypointIndex = 0;
}
public GameObject FindClosestWaypoint()
{
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag("Waypoint");
GameObject closest = null;
float distance = Mathf.Infinity;
Vector3 position = transform.position;
foreach (GameObject go in gos)
{
Vector3 diff = go.transform.position - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance)
{
closest = go;
distance = curDistance;
}
}
return closest;
}
private void SearchWalkPoint()
{
//Calculate random point in range
float randomZ = Random.Range(-walkPointRange, walkPointRange);
float randomX = Random.Range(-walkPointRange, walkPointRange);
walkPoint = new Vector3(transform.position.x + randomX, transform.position.y, transform.position.z + randomZ);
if (Physics.Raycast(walkPoint, -transform.up, 2f, whatIsGround))
walkPointSet = true;
}
private void ChasePlayer()
{
//patrol = false;
agent.SetDestination(player.position);
}
private void AttackPlayer()
{
//Make sure enemy doesn't move
agent.SetDestination(transform.position);
transform.LookAt(player);
if (!alreadyAttacked)
{
///Attack code here
///End of attack code
alreadyAttacked = true;
Invoke(nameof(ResetAttack), timeBetweenAttacks);
}
}
private void ResetAttack()
{
alreadyAttacked = false;
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, attackRange);
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(transform.position, sightRange);
}
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Waypoint" && !WpReached)
{
WpReached = true;
if (GameObject.Find("wp-" + (CurrentWpNumber + 1)) != null)
CurrentWpNumber += 1;
else
CurrentWpNumber = 0;
}
Debug.Log("Current Wp Target : " + CurrentWpNumber);
}
private void OnTriggerExit(Collider other)
{
if (other.tag == "Waypoint" && WpReached)
{
WpReached = false;
}
}
}
这是我添加的代码,用于在玩家超出范围时使 AI 返回航点。我将代码放在私有 voide lateup();
transform.LookAt(waypoints[CurrentWpNumber].position);
agent.SetDestination(waypoints[CurrentWpNumber].position);
感谢您花时间阅读本文。