Hello, i have an enemy patrolling on AI between different stations. It does it very well (Sepromene function).
In the Update section, i tried coding a lookat so that when my enemy comes between the mindistance and the maxdistance variables, it will orient to the player and follow it instead of continuing patrolling.
Here is the code i used, i have no error, but it just doesn’t work when my player comes near the enemy, it will just continue patrolling. (i have the good tag on my Player)
thanks for your help and time
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class NPCrandom2e : MonoBehaviour
{
public Transform player;
public int MaxDist = 10;
public int MinDist = 5;
int tempsdedetection = 10;
public int zonedemarche = 40;
UnityEngine.AI.NavMeshAgent Agent;
Vector3 positiondepart;
Vector3 destination;
void Start()
{
tempsdedetection = Random.Range(8, 16);
InvokeRepeating("Sepromene", 1.0f, tempsdedetection);
Agent = GetComponent<UnityEngine.AI.NavMeshAgent>();
positiondepart = this.transform.position;
Agent.acceleration = 20;
}
void Awake()
{
player = GameObject.FindGameObjectWithTag("Player").transform;
}
void Sepromene()
{
destination = positiondepart + new Vector3(Random.Range((int)-zonedemarche * 0.5f - 2,
(int)zonedemarche * 0.5f + 2), 0, Random.Range((int)-zonedemarche * 0.5f - 2, (int)zonedemarche * 0.5f + 2));
if (Agent.pathStatus != UnityEngine.AI.NavMeshPathStatus.PathInvalid)
{
Agent.SetDestination(destination);
}
}
void Update()
{
transform.LookAt(player);
if (Vector3.Distance(transform.position, player.position) >= MinDist)
{
transform.position += transform.forward * Time.deltaTime;
if (Vector3.Distance(transform.position, player.position) <= MaxDist)
{
Agent.SetDestination(player.position);
}
}
}
}
Seb