[UNET] [AI]我的机器人遇到了客户,但没有向他们走

时间:2018-07-11 16:31:59

标签: unity3d artificial-intelligence unity3d-unet unet navmesh

我的AI接受了两个玩家gameObjects计算哪一个更靠近他并一直走到他靠近他而不是面对他: 由于某些原因,即使主机距离很远,该漫游器也不会跟随客户端。

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 GameObject设置

enter image description here

感谢您抽出宝贵的时间来帮助我

0 个答案:

没有答案