Dead community,
Could someone help me out with implementing a wandering if the player is not in range.
because now the enemy will always walk to the player even if he is far away
i don’t have any experience with that
this is what i have so far
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.SceneManagement;
public class AdvanceAI : MonoBehaviour
{
Transform target;
[HideInInspector]
public NavMeshAgent agent;
Animator anim;
bool isDead = false;
public bool canAttack = true;
[SerializeField]
float chaseDistence = 2f;
[SerializeField]
float turnSpeed = 5f;
public float DamageAmount = 35;
[SerializeField]
float attacktime = 2f;
void Start()
{
target = GameObject.FindGameObjectWithTag("Player").transform;
agent = GetComponent<NavMeshAgent>();
anim = GetComponent<Animator>();
}
void Update()
{
float distance = Vector3.Distance(transform.position, target.position);
if (!isDead && !PlayerHealth.Singleton.isDead)
{
if (distance < chaseDistence && canAttack)
{
AttackPlayer();
}
else if (distance > chaseDistence)
{
ChasePlayer();
}
}
else
{
DisableEnemy();
}
}
public void EnemyDeathAnim()
{
isDead = true;
anim.SetTrigger("IsDead");
}
void ChasePlayer()
{
agent.updateRotation = true;
agent.updatePosition = true;
agent.SetDestination(target.position);
anim.SetBool("IsWalking", true);
anim.SetBool("IsAttacking", false);
}
void AttackPlayer()
{
agent.updateRotation = false;
Vector3 direction = target.position - transform.position;
direction.y = 0;
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction), turnSpeed * Time.deltaTime);
agent.updatePosition = false;
anim.SetBool("IsWalking", false);
anim.SetBool("IsAttacking", true);
StartCoroutine(AttackTime());
}
void DisableEnemy()
{
canAttack = false;
anim.SetBool("IsWalking", false);
anim.SetBool("IsAttacking", false);
}
IEnumerator AttackTime()
{
canAttack = false;
yield return new WaitForSeconds(0.5f);
PlayerHealth.Singleton.DamagePlayer(DamageAmount);
yield return new WaitForSeconds(attacktime);
canAttack = true;
}
}