【发布时间】:2021-02-06 02:20:44
【问题描述】:
我正在使用 c# 在 Unity 中创建一个 3D FPS 游戏。我有一个敌方 AI 使用 NavMeshAgent 巡逻一个区域。我有一种方法可以在地图上选择一个随机位置,然后告诉敌人去那个点,一旦它到达那个点,它应该在地图上选择另一个随机点,但是它只在某些时候有效.有时它会在该点附近停止,但即使没有任何东西告诉它停止,它也不会在该点停止,并且它不会选择新的点。有谁知道这个问题的解决方案吗?
这是我的脚本:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using Random = UnityEngine.Random;
public class EnemyController : MonoBehaviour
{
public NavMeshAgent agent;
public LayerMask groundMask;
//Patrolling Area
public Vector3 walkPoint;
private bool walkPointSet;
public float walkPointRange;
// Start is called before the first frame update
void Start()
{
agent = GetComponent<NavMeshAgent>();
}
// Update is called once per frame
void Update()
{
Patrol();
}
void Patrol()
{
if (!walkPointSet)
{
SearchWalkPoint();
}
Vector3 distanceToWalkPoint = transform.position - walkPoint;
//when walk point is reached
if (distanceToWalkPoint.magnitude < 1f)
{
walkPointSet = false;
}
}
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);
//checks if random walk point is inside of the map
if (Physics.Raycast(walkPoint, -transform.up, 3f, groundMask))
{
walkPointSet = true;
}
agent.SetDestination(walkPoint);
}
【问题讨论】: