0

我的 AI 正在使用两个玩家游戏对象,计算哪个玩家更接近并靠近他,直到他靠近而不是面对他:出于某种原因,即使主机真的很远,机器人也不会跟随客户端。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Networking;

public class EnemyController : NetworkBehaviour {

    public float lookRadius = 10f;
    NavMeshAgent agent;
    int indexOfShortest = 0;
    public GameObject[] players;
    // Use this for initialization
    void Start () {
        Debug.Log("START_HAS_ACCOMPLISHED");
        agent = GetComponent<NavMeshAgent>();
    }

    // Update is called once per frame
    void Update () {

        if (!isServer)
        {
            return;
        }
        if (NetworkManager.singleton.numPlayers >= 1)
        {
            players = GameObject.FindGameObjectsWithTag("Players");
            float[] distance = new float[NetworkManager.singleton.numPlayers];
            indexOfShortest = 0;
            for (int i = 0; i < distance.Length; i++)
            {
                distance[i] = Vector3.Distance(players[i].transform.position, transform.position);
                if (i == 0)
                {
                    indexOfShortest = 0;
                }
                if (i > 0 && distance[i] <= distance[i - 1])
                {
                    indexOfShortest = i;
                }
            }// Calculated distance from each player
            if (distance[indexOfShortest] <= lookRadius)
            {
                agent.isStopped = false;
                agent.SetDestination(players[indexOfShortest].transform.position); //If the player is in the radius chase
                if (distance[indexOfShortest] <= agent.stoppingDistance)
                {
                    //attack target
                    FaceTarget();
                }
            }

        }

    }


    void FaceTarget()
    {
        Vector3 direction = (players[indexOfShortest].transform.position - transform.position).normalized;
        Quaternion lookRotation = Quaternion.LookRotation(new Vector3(direction.x, 0, direction.z));
        transform.rotation = Quaternion.Slerp(transform.rotation,lookRotation,Time.deltaTime * 5f) ;
    }

 }

我的 AI 游戏对象设置

在此处输入图像描述

感谢您花时间帮助我

4

0 回答 0