using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.AI;
public class EnemyFollow2 : MonoBehaviour
{
public UnityEngine.AI.NavMeshAgent enemy;
public Transform player;
public LayerMask Ground, whatIsPlayer;
//Patroling
public Vector3 walkPoint;
bool walkPointSet;
public float walkPointRange;
//Attacking
public float timeBetweenAttacks;
bool alreadyAttacked;
public GameObject projectile;
//States
public float sightRange, attackRange;
public bool playerInSightRange, playerInAttackRange;
// Start is called before the first frame update
void Start()
{
}
private void Awake()
{
player = GameObject.Find("Player").transform;
}
// Update is called once per frame
void Update()
{
enemy.SetDestination(player.position);
//Check for sight and attack range
playerInSightRange = Physics.CheckSphere(transform.position, sightRange, whatIsPlayer);
playerInAttackRange = Physics.CheckSphere(transform.position, attackRange, whatIsPlayer);
if (!playerInSightRange && !playerInAttackRange) Patroling();
if (playerInSightRange && !playerInAttackRange) ChasePlayer();
if (playerInSightRange && playerInAttackRange) AttackPlayer();
}
private void Patroling()
{
if (!walkPointSet) SearchWalkPoint();
if (walkPointSet)
enemy.SetDestination(walkPoint);
Vector3 distanceToWalkPoint = transform.position - walkPoint;
//Walkpoint reached
if (distanceToWalkPoint.magnitude < 1f)
walkPointSet = false;
}
private void SearchWalkPoint()
{
//Calculate random point in range
float randomZ = Random.Range(-walkPointRange, walkPointRange);
float randomX = Random.Range(-walkPointRange, walkPointRange);
walkPoint = new Vector3(transform.position.x + randomX, transform.position.y, transform.position.z + randomZ);
if (Physics.Raycast(walkPoint, -transform.up, 2f, Ground))
walkPointSet = true;
}
private void ChasePlayer()
{
enemy.SetDestination(player.position);
}
private void AttackPlayer()
{
//Enemy doesn't move
enemy.SetDestination(transform.position);
transform.LookAt(player);
if (!alreadyAttacked)
{
Rigidbody rb = Instantiate(projectile, transform.position, Quaternion.identity).GetComponent<Rigidbody>();
rb.AddForce(player.position * 200f, ForceMode.Impulse);
rb.AddForce(transform.up * 0.001f, ForceMode.Impulse);
alreadyAttacked = true;
Invoke(nameof(ResetAttack), timeBetweenAttacks);
}
}
private void ResetAttack()
{
alreadyAttacked = false;
}
}
I dont have any errors but is there any reason he might be doing this?
hes looking at me too but the sphere comes out his but almost and shoots behind him.