Help, I am trying to make a code, where my enemy looks around for me, and then when he spots me, starts shooting slowly, but what ends up happening is from the start my enemy spam shoots me until I get 1 meter or closer to him, and when i back up he spam shoots me again! any help?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class Enemy : MonoBehaviour
{
public NavMeshAgent agent;
public Transform player;
public LayerMask whatIsGround, whatIsPlayer;
public GameObject enemybulletPrefab;
public float health;
//patrolling
public Vector3 walkPoint;
bool walkPointSet;
public float walkPointRange;
//attacking
public float timeBetweenAttacks;
bool alreadyAttacked;
//states
public float sightRange, attackRange;
public bool PlayerInSightRange, PlayerInAttackRange;
private void Awake()
{
player = GameObject.Find("Fps player").transform;
agent = GetComponent<NavMeshAgent>();
}
private void Patrolling()
{
if (!walkPointSet)
{
SearchWalkPoint();
}
if (walkPointSet)
{
agent.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, whatIsGround))
{
;
}
walkPointSet = true;
}
private void ChasePlayer()
{
agent.SetDestination(player.position);
}
private void Attackplayer()
{
//make sure enemy doesn't move
agent.SetDestination(transform.position);
transform.LookAt (player);
//shooting
GameObject bulletObject = Instantiate(enemybulletPrefab);
bulletObject.transform.position = transform.position + transform.forward;
bulletObject.transform.forward = transform.forward;
if (alreadyAttacked)
{
alreadyAttacked = true;
Invoke(nameof(ResetAttack), timeBetweenAttacks);
}
}
private void ResetAttack()
{
alreadyAttacked = false;
}
private void Update()
{
//checking if player is in sight or attack range
PlayerInSightRange = Physics.CheckSphere(transform.position, sightRange, whatIsPlayer);
PlayerInAttackRange = Physics.CheckSphere(transform.position, attackRange, whatIsPlayer);
if (!PlayerInAttackRange && !PlayerInAttackRange)
{
Patrolling();
}
if (!PlayerInAttackRange && !PlayerInAttackRange)
{
ChasePlayer();
}
if (!PlayerInAttackRange && !PlayerInAttackRange)
{
Attackplayer();
}
}
public void TakeDamage(int damage)
{ }
}