Question by
faithbarnettvr · Apr 19, 2021 at 07:48 PM ·
editor-scriptingpathfindingenemy ai
Patrol Script not Working
For some reason only my chasing aspect of my AI is working, but not the patrol, anyone know why? Thanks!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class EnemyAIV1 : MonoBehaviour
{
public NavMeshAgent agent;
public Animator animator;
public Transform playerHead;
public LayerMask whatIsGround, whatIsPlayer;
// Patrol
public Vector3 walkPoint;
bool walkPointSet = false;
public float walkPointRange;
//Attacking
public float timeBetweenAttacks;
bool alreadyAttacked;
//States
public float sightRange, attackRange;
public bool playerInSightRange, playerInAttackRange;
private void Awake()
{
playerHead = GameObject.Find("XR Rig").transform;
agent = GetComponent<NavMeshAgent>();
}
private void Update()
{
playerInSightRange = Physics.CheckSphere(transform.position, sightRange, whatIsPlayer);
playerInAttackRange = Physics.CheckSphere(transform.position, attackRange, whatIsPlayer);
if (!playerInSightRange && !playerInAttackRange) {Patroling(); }
if (playerInSightRange && !playerInAttackRange) {Chasing(); }
if (!playerInSightRange && !playerInAttackRange) {Attacking(); }
}
private void Patroling()
{
if (!walkPointSet)
{ SearchWalkPoint(); }
if (walkPointSet)
{
agent.SetDestination(walkPoint);
transform.LookAt(walkPoint);
animator.SetBool("IsWalking",true);
animator.SetBool("IsHitting", false);
}
Vector3 distanceToWalkPoint = transform.position - walkPoint;
if (distanceToWalkPoint.magnitude < 1f)
{walkPointSet = false;}
}
private void SearchWalkPoint()
{
float randZ = Random.Range(-walkPointRange, walkPointRange);
float randX = Random.Range(-walkPointRange, walkPointRange);
walkPoint = new Vector3(transform.position.x + randX, 0, transform.position.z + randZ);
if (Physics.Raycast(walkPoint, -1*transform.up, 2f, whatIsGround))
{
walkPointSet = true;
}
}
private void Chasing()
{
agent.SetDestination(playerHead.position);
transform.LookAt(playerHead.position);
animator.SetBool("IsWalking",true);
}
private void Attacking()
{
agent.SetDestination(transform.position);
animator.SetBool("IsWalking", false);
animator.SetBool("IsHitting", true);
transform.LookAt(playerHead);
if (!alreadyAttacked)
{
alreadyAttacked = true;
Invoke(nameof(ResetAttack), timeBetweenAttacks);
}
}
private void ResetAttack()
{
alreadyAttacked = false;
}
}
Comment
Your answer
Follow this Question
Related Questions
How to make enemy avoid walls? 1 Answer
astar pathfinding with groups 0 Answers
Pathfinding Set Up In Unity2D 0 Answers
Enemy can't move follow the path, A* algorithm for my game 0 Answers
Enemy pathfinding script for a 2D top down shooter game 0 Answers