触发追逐玩家后如何让我的AI返回最近的航点

如何解决触发追逐玩家后如何让我的AI返回最近的航点

你好,我是 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);

这是发生的错误

the error that happens

感谢您花时间阅读本文。

解决方法

通过简单的人工智能实现这一目标的常用方法是实现有限状态机 (FSM),其中每个行为都被划分为状态。有很多教程可以教你如何制作。

有了它,你可以拥有 ReturnToClosestWaypoint 状态,它会找到最近的 Waypoint,朝它移动,当足够接近时,将状态设置回 IdleState 或 PatrolState 之类的东西。

您的异常是通用数组/列表异常,它基本上是在告诉您您正在尝试从索引不存在的数组/列表中获取项目。

检查 CurrentWpNumber 是否不小于零且小于航点数组/列表的长度/大小。您的航点数组/列表也可能为空,因此您还可以在尝试访问数组之前检查数组的长度/大小是否大于零。

if(waypoints == null || waypoints.Length == 0){
    Debug.Log("waypoints array is empty!");
    return;
}

if(CurrentWpNumber < 0 || CurrentWpNumber >= waypoints.Length){
    Debug.Log("No waypoint with index " + CurrentWpNumber);
    return;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?