0

My AI is taking two player gameObjects calculates which one is closer and goes to him until he is close than he just faces him: For some reason the bot won't follow the client even if the host is really far away.

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) ;
    }

 }

My AI GameObject settings

enter image description here

Thank you for taking your time into helping me

  • Well, the bot won't move to the player because there ain't no code telling it to do so (or at least I didn't find it). I know it is called Artificial _Intelligence_, but that would be too much... – Rodrigo Rodrigues Jul 11 '18 at 17:06
  • well the agent.SetDestination does exactly this but to the position of the closest one @RodrigoRodrigues – Eyal Abramovitch Jul 11 '18 at 17:38

0 Answers0