I am trying to make it so the enemy navmeshagent.speed changes when he goes back to guarding so instead of chasing me by running which he does first, so after he suspicious he can casual walk back to his guarding spot.
I Am very novice when it comes to this, and I cant seem to get it to work, any help would be appreciated if you could point me in the right direction.
using System.Collections;
using System.Collections.Generic;
using RPG.Combat;
using RPG.Core;
using RPG.Movement;
using UnityEngine;
using UnityEngine.AI;
namespace RPG.Control
{
public class AIController : MonoBehaviour
{
[SerializeField] float chaseDistance = 5f;
[SerializeField] float suspicionTime = 3f;
[SerializeField] float WalkSpeed = 2f;
Fighter fighter;
GameObject player;
Health health;
Mover mover;
NavMeshAgent agent;
float currentSpeed;
Vector3 guardPostion;
float timeSinceLastSawPlayer = Mathf.Infinity;
private void Start()
{
fighter = GetComponent<Fighter>();
player = GameObject.FindWithTag("Player");
health = GetComponent<Health>();
mover = GetComponent<Mover>();
agent = GetComponent<NavMeshAgent>();
currentSpeed = agent.speed;
guardPostion = transform.position;
}
private void Update()
{
if (health.IsDead()) return;
if (InAttackRangeOfPlayer() && fighter.CanAttack(player))
{
timeSinceLastSawPlayer = 0;
AttackBehaviour();
}
else if (timeSinceLastSawPlayer < suspicionTime)
{
SuspicionBehaviour();
}
else
{
currentSpeed = WalkSpeed;
GuardBehaviour();
}
timeSinceLastSawPlayer += Time.deltaTime;
}
private void GuardBehaviour()
{
currentSpeed = WalkSpeed;
mover.StartMoveAction(guardPostion);
}
private void SuspicionBehaviour()
{
GetComponent<ActionScheduler>().CancelCurrentAction();
}
private void AttackBehaviour()
{
fighter.Attack(player);
}
private bool InAttackRangeOfPlayer()
{
float distanceToPlayer = Vector3.Distance(player.transform.position, transform.position);
return distanceToPlayer < chaseDistance;
}
//Called by Unity
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, chaseDistance);
}
}
}