Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

help with pacman Enemy AI

Discussion in 'Navigation' started by gdossantos87, May 11, 2015.

  1. gdossantos87

    gdossantos87

    Joined:
    Mar 18, 2014
    Posts:
    43
    helo guys, i'm trying to make the ghost wonder around the navigation without using waypoints but so far just manage to make de enemy ghost follow the player with the script

    NavMeshAgent nav;
    nav.SetDestination(player.position);

    my idea is to make the ghost chase the player only if they are in range and only then use the script nav.SetDestination(player.position);

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. publicclassEnemyAttack : MonoBehaviour
    5. {
    6. publicint attackDamage =100;
    7. publicTransform player;
    8. publicbool playerInRange;
    9. PlayerHealth playerHealth;
    10. // Use this for initialization
    11. void Awake ()
    12. {
    13. player =GameObject.FindGameObjectWithTag("Player").transform;
    14. playerHealth = player.GetComponent<PlayerHealth>();
    15. }
    16. // Update is called once per frame
    17. void Update () {
    18. }
    19. void OnTriggerEnter(Collider other)
    20. {
    21. if (other.gameObject.tag =="Player")
    22. {
    23. playerInRange =true;
    24. Debug.Log(playerInRange);
    25. }
    26. }
    27. void OnTriggerExit(Collider other)
    28. {
    29. if (other.gameObject.tag =="Player")
    30. {
    31. playerInRange =false;
    32. Debug.Log(playerInRange);
    33. }
    34. }
    35. void OnCollisionEnter(Collision col)
    36. {
    37. if (col.gameObject.name =="Player")
    38. {
    39. Attack();
    40. }
    41. }
    42. void Attack()
    43. {
    44. if (playerHealth.currentHealth >0)
    45. {
    46. playerHealth.TakeDamage(attackDamage);
    47. }
    48. }
    49. }
    50.  
     
  2. MysterySoftware

    MysterySoftware

    Joined:
    Sep 18, 2014
    Posts:
    46
    You can check whether or not the player is in range by using Vector3.Distance.

    Code (CSharp):
    1. if (Vector3.Distance (transform.position, player.position) <= someMaximumDistance) {
    2.     // The player is in range
    3. }