using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class EnemyAI : MonoBehaviour
{
public Transform target; // Player's transform
public float moveSpeed = 3f; // Speed of movement
public float rotationSpeed = 3f; // Speed of rotation
public float chaseRange = 10f; // Range within which enemy will start chasing
private Vector3 initialPosition; // Initial position of the enemy
private bool isChasing = false; // Flag to track whether enemy is chasing
void Start()
{
initialPosition = transform.position;
}
void Update()
{
// Calculate the distance between the player and the enemy
float distanceToTarget = Vector3.Distance(transform.position, target.position);
// If the player is within chase range, start chasing
if (distanceToTarget <= chaseRange)
{
isChasing = true;
}
if (isChasing)
{
Chase();
}
else
{
ReturnToInitialPosition();
}
}
void Chase()
{
// Rotate towards the player
Vector3 targetDirection = (target.position - transform.position).normalized;
Quaternion lookRotation = Quaternion.LookRotation(targetDirection);
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, rotationSpeed * Time.deltaTime);
// Move towards the player
transform.position += transform.forward * moveSpeed * Time.deltaTime;
}
void ReturnToInitialPosition()
{
// Rotate towards the initial position
Vector3 initialDirection = (initialPosition - transform.position).normalized;
Quaternion lookRotation = Quaternion.LookRotation(initialDirection);
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, rotationSpeed * Time.deltaTime);
// Move towards the initial position
transform.position += transform.forward * moveSpeed * Time.deltaTime;
// If the enemy reaches close to the initial position, stop chasing
if (Vector3.Distance(transform.position, initialPosition) <= 0.5f)
{
isChasing = false;
}
}
}