Search Unity

Question The enemy doesn't show movement and isn't attacking and idle when player is close

Discussion in 'Navigation' started by GGGamerMaster, Jun 6, 2023.

  1. GGGamerMaster

    GGGamerMaster

    Joined:
    Apr 16, 2022
    Posts:
    1
    this is the code, it isnt working

    using UnityEngine;
    using UnityEngine.AI;

    public class EnemyAI : MonoBehaviour
    {
    public NavMeshAgent agent;
    public Transform player;
    public LayerMask groundMask, playerLayer;
    public Vector3 walkPoint;
    bool isWalkPointSet;
    public float walkPointRange;
    public float timeBetweenAttacks;
    bool attacked;
    public float chaseRange, attackRange;
    bool inChaseRange, inAttackRange;
    public Animator animator;
    public LayerMask collisionLayer;

    private void Awake()
    {
    player = GameObject.Find("Player").transform;
    agent = GetComponent<NavMeshAgent>();
    animator = GetComponent<Animator>();
    }

    private void Update()
    {
    inChaseRange = Physics.CheckSphere(transform.position, chaseRange, playerLayer);
    inAttackRange = Physics.CheckSphere(transform.position, attackRange, playerLayer);

    if (!inAttackRange && !inChaseRange) { Patrol(); Walk(); }
    if (!inAttackRange && inChaseRange) { Chase(); Walk(); }
    if (inAttackRange && inChaseRange) { Attack(); Idle(); }
    }

    private void OnTriggerEnter(Collider other)
    {
    if (collisionLayer == (collisionLayer | (1 << other.gameObject.layer)))
    {
    GetHit();
    }
    }

    void Patrol()
    {
    if (!isWalkPointSet) SearchWalkPoint();

    if (isWalkPointSet)
    agent.SetDestination(walkPoint);

    Vector3 distanceToWalkPoint = transform.position - walkPoint;

    if (distanceToWalkPoint.magnitude < 1f)
    isWalkPointSet = false;
    }

    private void SearchWalkPoint()
    {
    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, groundMask))
    isWalkPointSet = true;
    }

    void Chase()
    {
    agent.SetDestination(player.position);
    }

    void Attack()
    {
    agent.SetDestination(transform.position);
    transform.LookAt(player);

    if (!attacked)
    {
    animator.SetBool("Attack", true);
    attacked = true;
    Invoke(nameof(ResetAttack), timeBetweenAttacks);
    }
    }

    void ResetAttack()
    {
    animator.SetBool("Attack", false);
    attacked = false;
    }

    void Walk()
    {
    animator.SetFloat("Speed", 1f);
    }

    void Idle()
    {
    animator.SetFloat("Speed", 0f);
    }

    void GetHit()
    {
    Debug.Log("Enemy is hit.");
    }
    }