so i am trying to make a game and coded a enemy ai script that patrols using navmesh and when it detects a player it comes to it and starts an attack animation but when that is playing it rotates for some reason it might be from the animation but i dont know anymore honestly here is my script maybe i got something wrong
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class EnemyAIPatrol : MonoBehaviour
{
NavMeshAgent agent;
GameObject player;
[SerializeField] LayerMask groundLayer, playerLayer;
Vector3 destPoint;
bool walkpointSet;
[SerializeField] float range;
[SerializeField] float sightRange, attackRange;
bool playerInSight, playerInAttackRange;
Animator animator;
BoxCollider boxCollider;
//Damage
ScrollHealth playerHealth;
// Start is called before the first frame update
void Start()
{
agent = GetComponent<NavMeshAgent>();
player = GameObject.Find("FirstPersonController");
animator = GetComponent<Animator>();
boxCollider = GetComponentInChildren<BoxCollider>();
playerHealth = player.GetComponentInChildren<ScrollHealth>();
}
// Update is called once per frame
void Update()
{
playerInSight = Physics.CheckSphere(transform.position, sightRange, playerLayer);
playerInAttackRange = Physics.CheckSphere(transform.position, attackRange, playerLayer);
if (!playerInSight && !playerInAttackRange) Patrol();
if (playerInSight && !playerInAttackRange) Chase();
if (playerInSight && playerInAttackRange) Attack();
}
void Attack()
{
if (!animator.GetCurrentAnimatorStateInfo(0).IsName("Z_Attack"))
{
animator.SetTrigger("Attack");
agent.SetDestination(transform.position);
}
}
void Chase()
{
agent.SetDestination(player.transform.position);
}
void Patrol()
{
if (!walkpointSet) SearchForDestination();
if (walkpointSet) agent.SetDestination(destPoint);
if (Vector3.Distance(transform.position, destPoint) < 1f) walkpointSet = false;
}
void SearchForDestination()
{
float z = Random.Range(-range, range);
float x = Random.Range(-range, range);
destPoint = new Vector3(transform.position.x + x, transform.position.y, transform.position.z + z);
if (Physics.Raycast(destPoint + Vector3.up * 10f, Vector3.down, 20f, groundLayer))
{
walkpointSet = true;
}
}
void EnableAttack()
{
boxCollider.enabled = true;
}
void DisableAttack()
{
boxCollider.enabled = false;
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
Debug.Log("Triggered by: " + other.gameObject.name);
var playerController = other.GetComponent<FirstPersonController>();
if (playerController != null)
{
Debug.Log("Player hit detected.");
if (playerHealth != null)
{
playerHealth.HealthAmount -= 33f;
playerHealth.HealthAmount = Mathf.Clamp(playerHealth.HealthAmount, 0f, 100f);
}
}
}
}
}
and this is how it looks after my enemy hits me about 4 times(at the begining is just facing me)
(dont ask about the enemy design)