public class MonsterScript : MonoBehaviour
{
public float walkRadius = 10f; // Radius within which the monster can walk randomly
public float chaseRange = 5f; // Range within which the monster will chase the player
public float speed = 3.5f; // Speed of the monster
public Transform player; // Reference to the player’s transform
private NavMeshAgent navMeshAgent;
private Vector3 targetPosition;
void Start()
{
navMeshAgent = GetComponent();
StartCoroutine(WalkRandomly());
}
void Update()
{
// Check if the player is within chase range
if (Vector3.Distance(transform.position, player.position) < chaseRange)
{
ChasePlayer();
}
}
private void ChasePlayer()
{
navMeshAgent.SetDestination(player.position);
}
private IEnumerator WalkRandomly()
{
while (true)
{
// Set a random target position within the walk radius
targetPosition = new Vector3(
transform.position.x + Random.Range(-walkRadius, walkRadius),
transform.position.y,
transform.position.z + Random.Range(-walkRadius, walkRadius)
);
// Move to the target position
navMeshAgent.SetDestination(targetPosition);
// Wait for a while before moving again
yield return new WaitForSeconds(Random.Range(2f, 5f));
}
}
}