I got the enemy to chase me, but halfway he jumps to the other side of the area or stays on the outside of the walkable area. New to coding so I'm not sure if its in the code or the NavmeshArea.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class EnemyController : MonoBehaviour
{
public float movementSpeed;
public GameObject Target;
public float lookRadius = 10f;
// Attack
public int AttackDamageMin;
public int AttackDamageMax;
public float AttackCooldownTimeMain;
public float AttackCooldownTime;
Transform target;
NavMeshAgent agent;
void Start()
{
target = PlayerManager.instance.player.transform;
agent = GetComponent();
}
// Update is called once per frame
void Update()
{
float distance = Vector3.Distance(target.position, transform.position);
if(distance < 30)
{
agent.SetDestination(target.position);
if (distance <= agent.stoppingDistance)
{
Facetraget();
}
transform.Translate(Vector3.forward * movementSpeed);
}
else
{
if (AttackCooldownTime > 0)
{
AttackCooldownTime -= Time.deltaTime;
}
else
{
AttackCooldownTime = AttackCooldownTimeMain;
AttackTarget();
}
}
}
void AttackTarget ()
{
Target.transform.GetComponent().TakeDamage(Random.Range(AttackDamageMin, AttackDamageMax));
}
void Facetraget ()
{
Vector3 direction = (target.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);
}
void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, lookRadius);
}
}
↧