Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

A* AI and keeping the player at range

Discussion in 'Scripting' started by NxG_Anima, Sep 23, 2017.

  1. NxG_Anima

    NxG_Anima

    Joined:
    Dec 3, 2016
    Posts:
    3
    Hello everyone! Im following a tutorial on youtube for making my first 2D platformer and decided to make a flying AI with that kind of script. It all works great, and i was able to make a makeshift "player search" coroutine. My problem is that i would like the AI to stay away from the player in a certain range so to have an Ai that bumps into the player and explodes and one that stays at range shooting. I really tried other solutions found in here and else, but i can't insert those because of A* (?) Here is the script. Any help / suggestion on the matter would be great, thanks!
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using Pathfinding;
    5.  
    6. [RequireComponent (typeof(Rigidbody2D))]
    7. [RequireComponent (typeof(Seeker))]
    8.  
    9. public class EnemyFlyer : MonoBehaviour {
    10.  
    11.     private Transform target;
    12.  
    13.     public float updateRate = 2f;
    14.     public float range = 12f ;
    15.     private Seeker seeker;
    16.     private Rigidbody2D rb;
    17.     public Path path;
    18.     private int currentWaypoint = 0;
    19.     public float speed = 100f;
    20.     public ForceMode2D fmode;
    21.  
    22.     [HideInInspector]
    23.     public bool pathIsEnded = false;
    24.  
    25.     public float nextWaypointDistance = 3;
    26.  
    27.     void Start (){
    28.         seeker = GetComponent<Seeker> ();
    29.         rb = GetComponent<Rigidbody2D> ();
    30.         InvokeRepeating ("UpdateTarget", 0f, 0.5f);
    31.         StartCoroutine (UpdatePath ());
    32.     }
    33.  
    34.     IEnumerator UpdatePath () {
    35.         if (target == null) {
    36.             yield break;
    37.         }
    38.  
    39.         seeker.StartPath (transform.position, target.position , OnPathComplete);
    40.  
    41.         yield return new WaitForSeconds (1f / updateRate);
    42.         StartCoroutine (UpdatePath ());
    43.     }
    44.  
    45.     public void OnPathComplete (Path p) {
    46.         Debug.Log ("Path assigned. Any Errors?" + p.error);
    47.         if (!p.error) {
    48.             path = p;
    49.             currentWaypoint = 0;
    50.         }
    51.     }
    52.  
    53.     void UpdateTarget() {
    54.         GameObject enemy = GameObject.FindGameObjectWithTag ("Player");
    55.         float shortestDistance = Mathf.Infinity;
    56.         GameObject nearestEnemy = null;
    57.         float enemyDistance = Vector3.Distance (transform.position, enemy.transform.position);
    58.         if (enemyDistance < shortestDistance) {
    59.             shortestDistance = enemyDistance;
    60.             nearestEnemy = enemy;
    61.         }
    62.         if (nearestEnemy != null && shortestDistance <= range) {
    63.             target = nearestEnemy.transform;
    64.             range = 15f;
    65.             seeker.StartPath (transform.position, target.position, OnPathComplete);
    66.         } else {
    67.             target = null;
    68.         }
    69.  
    70.     }
    71.  
    72.     void StartPath(){
    73.         seeker.StartPath (transform.position, target.position, OnPathComplete);
    74.     }
    75.  
    76.     void FixedUpdate () {
    77.  
    78.         if (target == null) {
    79.             range = 12f;
    80.             return;
    81.         }
    82.            
    83.         //TODO: Always look at player
    84.  
    85.         if (path == null)
    86.             return;
    87.  
    88.         if (currentWaypoint >= path.vectorPath.Count) {
    89.             if (pathIsEnded)
    90.                 return;
    91.            
    92.             Debug.Log ("End of Path.");
    93.             pathIsEnded = true;
    94.             return;
    95.         }
    96.         pathIsEnded = false;
    97.  
    98.         Vector3 dir = (path.vectorPath [currentWaypoint] - transform.position).normalized;
    99.         dir *= speed * Time.fixedDeltaTime;
    100.  
    101.         rb.AddForce (dir, fmode);
    102.  
    103.         float dist = Vector3.Distance (transform.position, path.vectorPath [currentWaypoint]);
    104.         if (dist < nextWaypointDistance) {
    105.             currentWaypoint++;
    106.             return;
    107.         }
    108.  
    109.    
    110.     }
    111.  
    112.     void OnDrawGizmosSelected (){
    113.         Gizmos.color = Color.green;
    114.         Gizmos.DrawWireSphere (transform.position, range);
    115.     }
    116.  
    117.  
    118. }
    119.