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. Join us on Dec 8, 2022, between 7 am & 7 pm EST, in the DOTS Dev Blitz Day 2022 - Q&A forum, Discord, and Unity3D Subreddit to learn more about DOTS directly from the Unity Developers.
    Dismiss Notice
  3. Have a look at our Games Focus blog post series which will show what Unity is doing for all game developers – now, next year, and in the future.
    Dismiss Notice

Question Why won't the enemy chase the main player?

Discussion in 'Scripting' started by anonymouself543, Nov 25, 2022.

  1. anonymouself543

    anonymouself543

    Joined:
    Jun 16, 2021
    Posts:
    8
    I am trying to make an enemy ai chase the main player

    here is the enemy ai -
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Enemy : Mover
    6. {
    7.     // Experience
    8.     public int xpValue = 1;
    9.  
    10.     // Logic
    11.     public float triggerLength = 0.3f;
    12.     public float chaseLength = 1;
    13.     private bool chasing;
    14.     private bool collidingWithPlayer;
    15.     private Transform playerTransform;
    16.     private Vector3 startingPosition;
    17.  
    18.     // Hitbox
    19.     public ContactFilter2D filter;
    20.     private BoxCollider2D hitbox;
    21.     private Collider2D[] hits = new Collider2D[10];
    22.  
    23.     protected override void Start()
    24.     {
    25.         base.Start();
    26.         playerTransform = GameManager.instance.player.transform;
    27.         startingPosition = transform.position;
    28.         hitbox = transform.GetChild(0).GetComponent<BoxCollider2D>();
    29.     }
    30.  
    31.     protected void FixedUpdate()
    32.     {
    33.         // Is the player in range?
    34.         if (Vector3.Distance(playerTransform.position, startingPosition) < chaseLength)
    35.         {
    36.             if (Vector3.Distance(playerTransform.position, startingPosition) < triggerLength)
    37.                 chasing = true;
    38.  
    39.             if (chasing)
    40.             {
    41.                 if (!collidingWithPlayer)
    42.                 {
    43.                     UpdateMotor((playerTransform.position - transform.position).normalized);
    44.                 }
    45.             }
    46.             else
    47.             {
    48.                 UpdateMotor(startingPosition - transform.position);
    49.             }
    50.         }
    51.         else
    52.         {
    53.             UpdateMotor(startingPosition - transform.position);
    54.             chasing = false;
    55.         }
    56.  
    57.         // Check for overlaps
    58.         collidingWithPlayer = false;
    59.         hitbox.OverlapCollider(filter, hits);
    60.         for (int i = 0; i < hits.Length; i++)
    61.         {
    62.             if (hits[i] == null)
    63.                 continue;
    64.  
    65.             if (hits[i].tag == "Player" && hits[i].name == "Player")
    66.             {
    67.                 collidingWithPlayer = true;
    68.             }
    69.  
    70.             // the array is not cleaned up, do it yourself
    71.             hits[i] = null;
    72.         }
    73.     }
    74.  
    75.  
    76.     protected override void Death()
    77.     {
    78.         Destroy(gameObject);
    79.         GameManager.instance.Grantxp(xpValue);
    80.         GameManager.instance.ShowText("+" + xpValue + " xp", 30, new Color(0.7169f, 0f, 0.7169f), transform.position, Vector3.up * 25, 1.0f);
    81.     }
    82. }
    and here is the player script -
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class CharacterController2D : Fighter
    6. {
    7.     [SerializeField] private LayerMask dashLayerMask;
    8.  
    9.     private Rigidbody2D rigidbody2D;
    10.     private Vector3 moveDir;
    11.     private Vector3 lastMoveDir;
    12.     private bool isDashButtonDown;
    13.     private bool isAlive = true;
    14.  
    15.     private void Awake()
    16.     {
    17.         rigidbody2D = GetComponent<Rigidbody2D>();
    18.     }
    19.  
    20.     private void Update()
    21.     {
    22.         float moveX = 0f;
    23.         float moveY = 0f;
    24.         if (Input.GetKey(KeyCode.W))
    25.         {
    26.             moveY = 0.005f;
    27.         }
    28.  
    29.         if (Input.GetKey(KeyCode.S))
    30.         {
    31.             moveY = -0.005f;
    32.         }
    33.  
    34.         if (Input.GetKey(KeyCode.A))
    35.         {
    36.             moveX = -0.005f;
    37.         }
    38.  
    39.         if (Input.GetKey(KeyCode.D))
    40.         {
    41.             moveX = +0.005f;
    42.         }
    43.  
    44.         moveDir = new Vector3(moveX, moveY).normalized;
    45.         if (moveX != 0 || moveY != 0)
    46.         {
    47.             lastMoveDir = moveDir;
    48.         }
    49.  
    50.         if (Input.GetKeyDown(KeyCode.Space))
    51.         {
    52.             isDashButtonDown = true;
    53.         }
    54.  
    55.         // Swap sprite direction, wether you're going right or left
    56.         if(moveDir.x > 0)
    57.             transform.localScale = Vector3.one;
    58.         else if(moveDir.x < 0)
    59.             transform.localScale = new Vector3(-1, 1, 1);
    60.     }
    61.  
    62.     private void FixedUpdate()
    63.     {
    64.         rigidbody2D.velocity = moveDir;
    65.  
    66.         if (isDashButtonDown)
    67.         {
    68.             float dashAmount = 0.3f;
    69.             Vector3 dashPosition = transform.position + lastMoveDir * dashAmount;
    70.  
    71.             RaycastHit2D raycastHit2d = Physics2D.Raycast(transform.position, lastMoveDir, dashAmount, dashLayerMask);
    72.             if (raycastHit2d.collider != null)
    73.             {
    74.                 dashPosition = raycastHit2d.point;
    75.             }
    76.  
    77.             rigidbody2D.MovePosition(dashPosition);
    78.             isDashButtonDown = false;
    79.         }
    80.     }
    81.  
    82.     public void OnLevelUp()
    83.     {
    84.         maxHitpoint++;
    85.         hitpoint = maxHitpoint;
    86.         GameManager.instance.OnHitpointChange();
    87.     }
    88.  
    89.     public void SetLevel(int level)
    90.     {
    91.         for (int i = 0; i < level; i++)
    92.             OnLevelUp();
    93.     }
    94.  
    95.     protected override void ReceiveDamage(Damage dmg)
    96.     {
    97.         if (!isAlive)
    98.             return;
    99.  
    100.         base.ReceiveDamage(dmg);
    101.         GameManager.instance.OnHitpointChange();
    102.     }
    103.  
    104.     public void Heal(int healingAmount)
    105.     {
    106.         if (hitpoint == maxHitpoint)
    107.             return;
    108.  
    109.         hitpoint += healingAmount;
    110.         if (hitpoint > maxHitpoint)
    111.             hitpoint = maxHitpoint;
    112.         GameManager.instance.ShowText("+" + healingAmount.ToString() + " hp", 30, new Color(0.4718f, 1f, 0.2663f), transform.position, Vector3.up * 25, 1.0f);
    113.         GameManager.instance.OnHitpointChange();
    114.     }
    115.  
    116.     public void Respawn()
    117.     {
    118.         Heal(maxHitpoint);
    119.         isAlive = true;
    120.         lastImmune = Time.time;
    121.     }
    122. }
    and lastly here is the gamemanager script -
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.SceneManagement;
    5.  
    6. public class GameManager : MonoBehaviour
    7. {
    8.     public static GameManager instance;
    9.     private void Awake()
    10.     {
    11.         if (GameManager.instance != null)
    12.         {
    13.             Destroy(gameObject);
    14.             return;
    15.         }
    16.  
    17.         instance = this;
    18.         SceneManager.sceneLoaded += LoadState;
    19.         DontDestroyOnLoad(gameObject);
    20.     }
    21.  
    22.     // Resources
    23.     public List<Sprite> playerSprites;
    24.     public List<Sprite> weaponSprites;
    25.     public List<int> weaponPrices;
    26.     public List<int> xpTable;
    27.  
    28.     // References
    29.     public CharacterController2D player;
    30.     public RectTransform hitpointBar;
    31.     public Animator deathMenuAnim;
    32.     public FloatingTextManager floatingTextManager;
    33.  
    34.     // public weapon weapon...
    35.  
    36.     // Logic
    37.     public int gold;
    38.     public int experience;
    39.  
    40.     // Floating text
    41.     public void ShowText(string msg, int fontSize, Color color, Vector3 position, Vector3 motion, float duration)
    42.     {
    43.         floatingTextManager.Show(msg, fontSize, color, position, motion, duration);
    44.     }
    45.  
    46.     // Hitpoint bar
    47.     public void OnHitpointChange()
    48.     {
    49.         float ratio = (float)player.hitpoint / (float)player.maxHitpoint;
    50.         hitpointBar.localScale = new Vector3(ratio, 1, 1);
    51.     }
    52.  
    53.     // Experience
    54.     public int GetCurrentLevel()
    55.     {
    56.         int r = 0;
    57.         int add = 0;
    58.  
    59.         while (experience >= add)
    60.         {
    61.             add += xpTable[r];
    62.             r++;
    63.  
    64.             if (r == xpTable.Count)
    65.                 return r;
    66.         }
    67.  
    68.         return r;
    69.     }
    70.    
    71.     public int GetXpToLevel(int level)
    72.     {
    73.         int r = 0;
    74.         int xp = 0;
    75.  
    76.         while (r < level)
    77.         {
    78.             xp += xpTable[r];
    79.             r++;
    80.         }
    81.  
    82.         return xp;
    83.     }
    84.  
    85.     public void Grantxp(int xp)
    86.     {
    87.         int currlevel = GetCurrentLevel();
    88.         experience += xp;
    89.         if (currlevel < GetCurrentLevel());
    90.             OnLevelUp();
    91.        
    92.     }
    93.  
    94.     public void OnLevelUp()
    95.     {
    96.         GameManager.instance.ShowText("Level Up!", 30, new Color(0.7169f, 0f, 0.7169f), transform.position, Vector3.up * 25, 1.5f);
    97.         player.OnLevelUp();
    98.     }
    99.  
    100.     // DeathMenu and respawn
    101.     public void Respawn()
    102.     {
    103.         deathMenuAnim.SetTrigger("Hide");
    104.         UnityEngine.SceneManagement.SceneManager.LoadScene("Main");
    105.         player.Respawn();
    106.     }
    107.  
    108.     // Save state
    109.     public void SaveState()
    110.     {
    111.         string s = "";
    112.  
    113.         s += "0" + "|";
    114.         s += gold.ToString() + "|";
    115.         s += experience.ToString() + "|";
    116.         s += "0";
    117.  
    118.         PlayerPrefs.SetString("SaveState", s);
    119.     }
    120.     public void LoadState(Scene s, LoadSceneMode mode)
    121.     {
    122.         //player.transform.position = GameObject.Find("SpawnPoint").transform.position;
    123.  
    124.         if (!PlayerPrefs.HasKey("SaveState"))
    125.             return;
    126.  
    127.         string[] data = PlayerPrefs.GetString("SaveState").Split('|');
    128.  
    129.         // Change player skin
    130.         gold = int.Parse(data[1]);
    131.  
    132.         // Experience
    133.         experience = int.Parse(data[2]);
    134.         if (GetCurrentLevel() != 1)
    135.             player.SetLevel(GetCurrentLevel());
    136.  
    137.         // Change the weapon level
    138.  
    139.     }
    140. }
    everything like the damage receival and output works its just that the enemy won't chase my player

    thanks in advance for helping.
     
  2. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    8,130
    add some debug logs and Debug.DrawLine() to see whats happening and where all the positions are,
    in enemy script:
    does the first if' return true? (and then 2nd, 3rd, 4th if)