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. Dismiss Notice

Enemy Aggro Ranges

Discussion in 'Scripting' started by Ragerik, Nov 14, 2016.

  1. Ragerik

    Ragerik

    Joined:
    Nov 14, 2016
    Posts:
    21
    Hi guys I am a first time poster and have just recently over the last 2 months starting fiddling with Unity so I have limited scripting/ C# knowledge. So I am trying to implement a script in a 2D game that when the Player steps within the enemy's box collider they will start to shoot at him. I have tested the script to make sure the bullets instantiate correctly with physics moving them across the negative on the X axis with a cooldown between shots This code works perfectly. However, once the game is initiated the enemies have unlimited ranges and shoot while not on screen. I was instructed by my game dev buddy that I should use a Vector3.Distance versus a linecast for aggro range. Once i implemented it the bullets no longer act correctly. Now the bullet instantiates but no longer has any phsyics and just stops in mid-air right in font of its spawn point. If I have left out any keen information please let me know below.
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using UnityEngine.UI;
    4. using System.Collections;
    5.  
    6. public class EnemyMovementController : MonoBehaviour {
    7.  
    8.     public Text nadeCount;
    9.  
    10.  
    11.     //facing
    12.     public GameObject enemyGraphic;
    13.  
    14.     bool facingRight = true;
    15.  
    16.     //attacking
    17.     Rigidbody2D enemyRB;
    18.     public GameObject bullet;
    19.     public Transform bulletSpawn;
    20.     public bool shoot = true;
    21.     bool check = true;
    22.     GameObject player;
    23.     GameObject enemy;
    24.     bool canShoot;
    25.     float fireRate = 3f;
    26.     float nextFire;
    27.     float range = 10f;
    28.     string playerDistance;
    29.  
    30.     // Use this for initialization
    31.     void Start () {
    32.         enemyRB = GetComponent<Rigidbody2D> ();
    33.         player = GameObject.FindGameObjectWithTag ("Player");
    34.         enemy = GameObject.FindGameObjectWithTag ("Enemy");
    35.         Vector3.Distance (transform.position,  player.transform.position);
    36.     }
    37.  
    38.     // Update is called once per frame
    39.     void Update ()
    40.     {
    41.  
    42.     //    if (Time.time > nextFlipChance) {
    43.  
    44.     //        if (Random.Range (0, 10) >= 5)
    45.     //            nextFlipChance = Time.time + flipTime;
    46.         //}
    47.  
    48.  
    49.         //if (Time.time >= nextFire) {
    50.  
    51.             //    nextFire = Time.time + fireRate;
    52.             //    fireGun();
    53.  
    54.    
    55.    
    56.    
    57.  
    58.     }
    59.  
    60.    
    61.  
    62.  
    63.  
    64.  
    65.  
    66.  
    67.     void fireGun(){
    68.  
    69.  
    70.        
    71.  
    72.    
    73.             GameObject tempBullet;
    74.  
    75.                 tempBullet = Instantiate (bullet, bulletSpawn.transform.position, bulletSpawn.transform.rotation) as GameObject;
    76.  
    77.                 Rigidbody2D tempRB;
    78.                 tempRB = tempBullet.GetComponent<Rigidbody2D> ();
    79.    
    80.  
    81.             if (!facingRight){
    82.                 tempRB.AddForce (player.transform.position - enemy.transform.position* 2f * Time.deltaTime, ForceMode2D.Impulse);
    83.  
    84.                 Destroy (tempBullet, 2f);
    85.        
    86.            
    87.  
    88.             }
    89.  
    90.         }
    91.    
    92.  
    93.     void OnTriggerEnter2D(){
    94.  
    95.         if (Vector3.Distance (transform.position, player.transform.position) <= range)
    96.         {
    97.        
    98.  
    99.             if (Time.time >= nextFire) {
    100.  
    101.                 nextFire = Time.time + fireRate;
    102.                 fireGun();
    103.  
    104.  
    105.  
    106.  
    107.  
    108.             }
    109.            
    110.             }
    111.             /*GameObject tempBullet;
    112.  
    113.        
    114.    
    115.         }
    116.         /*
    117.         */        
    118.  
    119.  
    120.             //}
    121.         //}
    122.  
    123.  
    124.  
    125. //}
    126.  
    127.  
    128. }
    129.  
    130.  
    131. }
    132.  
     
    Last edited: Nov 14, 2016
  2. HolBol

    HolBol

    Joined:
    Feb 9, 2010
    Posts:
    2,888
    Format your code please.

    All you need to do is calculate the distance between the two vectors of the transforms you want to check and stick that in a conditional. Easy.
     
  3. Ragerik

    Ragerik

    Joined:
    Nov 14, 2016
    Posts:
    21
    Please excuse my lack of etiquette but, what do you mean by format my code? Correct me if im wrong do i stick the code:


    if (Vector3.Distance (transform.position, player.transform.position) <= range)
    {

    if (Time.time >= nextFire) {

    nextFire = Time.time + fireRate;
    fireGun();



    into a if/then cond.?Or is it:




    if (!facingRight){
    tempRB.AddForce (player.transform.position - enemy.transform.position* 2f * Time.deltaTime, ForceMode2D.Impulse);


    Sorry if I am not following conventions on the Unity forums; I am not sure the proper way to address issues and am noob.
     
  4. HolBol

    HolBol

    Joined:
    Feb 9, 2010
    Posts:
    2,888
    You're looking for this.

    And your code should come out looking like this:

    Code (csharp):
    1.  
    2. int foo = 1;
    3. int bar = 2;
    4.  
    5. return foo + bar;
    6.  
     
  5. Ragerik

    Ragerik

    Joined:
    Nov 14, 2016
    Posts:
    21
    Okay I reformatted it thank you for the tip. Correct me if I am wrong after looking at my post I am thinking of putting the this into the if/then cond.

    Code (csharp):
    1.  
    2. void OnTriggerEnter2D(){
    3.  
    4.         if (Vector3.Distance (transform.position, player.transform.position) <= range)
    5.         {
    6.            
    7.  
    8.             if (Time.time >= nextFire) {
    9.  
    10.                 nextFire = Time.time + fireRate;
    11.                  fireGun();
    12.  
    13.                 }
    14.  
    So changed the code to:

    Code (csharp):
    1.  
    2. void OnTriggerEnter2D(){
    3.  
    4.         if (Vector3.Distance (transform.position, player.transform.position) <= range)
    5.         {
    6.            
    7.  
    8.             if (Time.time >= nextFire) {
    9.  
    10.                 nextFire = Time.time + fireRate;
    11.                 return fireGun();
    12.  
    13.                 }
    14.  
    15. Followed by the error "EnemyMovementController.OnTriggerEnter " must not be followed by any expression when return method is void
     
    Last edited: Nov 14, 2016
  6. HolBol

    HolBol

    Joined:
    Feb 9, 2010
    Posts:
    2,888
    Should be fine, just remember to close OnTriggerEnter2D() because you've missed the end brace.
     
  7. Ragerik

    Ragerik

    Joined:
    Nov 14, 2016
    Posts:
    21
    So I closed the brace but the error:

    Assets/Scripts/EnemyMovementController.cs(101,33): error CS0127: `EnemyMovementController.OnTriggerEnter2D()': A return keyword must not be followed by any expression when method returns void.

    I read an explaination online of what this means. Void does not return anything. What keyword should I use for my function when it is declared? I saw someone use uLink.Whatever Is there also a proper methodology that follows this syntax?
     
    Last edited: Nov 14, 2016
  8. HolBol

    HolBol

    Joined:
    Feb 9, 2010
    Posts:
    2,888
    Post the whole code. Look at line 101 and see what you're doing wrong.
     
  9. Ragerik

    Ragerik

    Joined:
    Nov 14, 2016
    Posts:
    21
    I saw a post where someone put a return keyword at the end I wasn't sure if that was needed.

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using UnityEngine.UI;
    4. using System.Collections;
    5.  
    6. public class EnemyMovementController : MonoBehaviour {
    7.  
    8.     public Text nadeCount;
    9.  
    10.  
    11.     //facing
    12.     public GameObject enemyGraphic;
    13.  
    14.     bool facingRight = true;
    15.  
    16.     //attacking
    17.     Rigidbody2D enemyRB;
    18.     public GameObject bullet;
    19.     public Transform bulletSpawn;
    20.     public bool shoot = true;
    21.     bool check = true;
    22.     GameObject player;
    23.     GameObject enemy;
    24.     bool canShoot;
    25.     float fireRate = 3f;
    26.     float nextFire;
    27.     float range = 10f;
    28.     string playerDistance;
    29.  
    30.     // Use this for initialization
    31.     void Start () {
    32.         enemyRB = GetComponent<Rigidbody2D> ();
    33.         player = GameObject.FindGameObjectWithTag ("Player");
    34.         enemy = GameObject.FindGameObjectWithTag ("Enemy");
    35.         Vector3.Distance (transform.position,  player.transform.position);
    36.     }
    37.  
    38.     // Update is called once per frame
    39.     void Update ()
    40.     {
    41.  
    42.     //    if (Time.time > nextFlipChance) {
    43.  
    44.     //        if (Random.Range (0, 10) >= 5)
    45.     //            nextFlipChance = Time.time + flipTime;
    46.         //}
    47.  
    48.  
    49.         //if (Time.time >= nextFire) {
    50.  
    51.             //    nextFire = Time.time + fireRate;
    52.             //    fireGun();
    53.  
    54.      
    55.      
    56.      
    57.  
    58.     }
    59.  
    60.      
    61.  
    62.  
    63.  
    64.  
    65.  
    66.  
    67.  
    68.     void fireGun(){
    69.  
    70.  
    71.          
    72.  
    73.      
    74.             GameObject tempBullet;
    75.  
    76.                 tempBullet = Instantiate (bullet, bulletSpawn.transform.position, bulletSpawn.transform.rotation) as GameObject;
    77.  
    78.                 Rigidbody2D tempRB;
    79.                 tempRB = tempBullet.GetComponent<Rigidbody2D> ();
    80.      
    81.  
    82.             if (!facingRight){
    83.                 tempRB.AddForce (player.transform.position - enemy.transform.position* 2f * Time.deltaTime, ForceMode2D.Impulse);
    84.  
    85.                 Destroy (tempBullet, 2f);
    86.          
    87.              
    88.  
    89.             }
    90.  
    91.         }
    92.      
    93.  
    94.     void OnTriggerEnter2D(){
    95.  
    96.         if (Vector3.Distance (transform.position, player.transform.position) <= range) {
    97.          
    98.  
    99.             if (Time.time >= nextFire) {
    100.  
    101.                 nextFire = Time.time + fireRate;
    102.                 return fireGun ();
    103.  
    104.             }
    105.              
    106.         }
    107.  
    108.         /*GameObject tempBullet;
    109.  
    110.          
    111.      
    112.         }
    113.         /*
    114.         */          
    115.  
    116.  
    117.         //}
    118.         //}
    119.  
    120.  
    121.  
    122. //}
    123.  
    124.  
    125.  
    126.  
    127.  
    128.  
    129.  
    130.     }
    131.  
    132.  
    133.     }
    134.  
     
  10. HolBol

    HolBol

    Joined:
    Feb 9, 2010
    Posts:
    2,888
    You've put a return statement in OnTriggerEnter2D() which is a void function and therefore does not need a return statement. What exactly are you trying to do here?
     
  11. Ragerik

    Ragerik

    Joined:
    Nov 14, 2016
    Posts:
    21
    AJust trying to get the bullet to instantiate and shoot I tried it as a troubleshoot. I just tested it and there's a lag when the enemy shoots but theres no physics. It spawns but does not move. when i reverse the direction the bullet shoots the code works perfectly instantaneously except the enemy shoots itself going toward the positive x
     
  12. HolBol

    HolBol

    Joined:
    Feb 9, 2010
    Posts:
    2,888
    Should you not just delete the return statement? You're not returning the result of that function, you are calling that function.
     
  13. Ragerik

    Ragerik

    Joined:
    Nov 14, 2016
    Posts:
    21
    Okay so I did what you said and it DOES work. The issue now is for some reason they stop exactly where they are instantiated. Im checking the physics to make sure its applied to the prefab. It's weird I used the same prefab bullet for the hero and the enemies.
     
  14. HolBol

    HolBol

    Joined:
    Feb 9, 2010
    Posts:
    2,888
    Then there's something wrong with your facingRight code, as that is the only condition in which things have force added to them.
     
    Ragerik likes this.
  15. Ragerik

    Ragerik

    Joined:
    Nov 14, 2016
    Posts:
    21
    Even if it worked before adding the aggro range? It's the same code I used for my Player and he shoots perfectly fine.

    EDIT:
    Code (csharp):
    1.  
    2. if (!facingRight){
    3.                 tempRB.AddForce (player.transform.position - enemy.transform.position* 2f * Time.deltaTime, ForceMode2D.Impulse);
    4.  
    I used the position of the player vs the position of the enemy
     
  16. HolBol

    HolBol

    Joined:
    Feb 9, 2010
    Posts:
    2,888
    The only time your fireGun() code will be called is when you are in that aggro range.
     
  17. Ragerik

    Ragerik

    Joined:
    Nov 14, 2016
    Posts:
    21
    I think I see now this my character code i pulled from:

    Code (csharp):
    1.  
    2. void fireGun ()
    3.     {
    4.         GameObject tempBullet;
    5.  
    6.         tempBullet = Instantiate (bullet, bulletSpawn.transform.position, bulletSpawn.transform.rotation) as GameObject;
    7.  
    8.         Rigidbody2D tempRB;
    9.         tempRB = tempBullet.GetComponent<Rigidbody2D> ();
    10.  
    11.         if(facingRight)
    12.             tempRB.AddForce (new Vector2 (1, 0) * 50f * Time.deltaTime, ForceMode2D.Impulse);
    13.         else if(!facingRight)
    14.             tempRB.AddForce (new Vector2 (-1, 0) * 50f * Time.deltaTime, ForceMode2D.Impulse);
    15.  
    16.         Destroy (tempBullet, 2f);
    17.  
    On this one I told it to addforce to the distance between the player transform and the enemy transform with the x,yz conditions. While the bullet instantiates it will not move because it has not been told to when the function is called.

    Code (csharp):
    1.  
    2. void fireGun(){
    3.  
    4.  
    5.          
    6.  
    7.      
    8.             GameObject tempBullet;
    9.  
    10.                 tempBullet = Instantiate (bullet, bulletSpawn.transform.position, bulletSpawn.transform.rotation) as GameObject;
    11.  
    12.                 Rigidbody2D tempRB;
    13.                 tempRB = tempBullet.GetComponent<Rigidbody2D> ();
    14.      
    15.  
    16.             if (!facingRight){
    17.                 tempRB.AddForce (player.transform.position - enemy.transform.position* 2f * Time.deltaTime, ForceMode2D.Impulse);
    18.  
    19.                 Destroy (tempBullet, 2f);
    20.          
    21.              
    22.  
    23.             }
    24.  
    25.         }
    26.  
     
  18. Ragerik

    Ragerik

    Joined:
    Nov 14, 2016
    Posts:
    21
    So the aggro range works but the last issue is the bullet instantiation. They have no physics and stay static right at the spawn point
     
  19. Ragerik

    Ragerik

    Joined:
    Nov 14, 2016
    Posts:
    21
    Fishman92 I GOT IT!!!! Thank you so much man the range works consistently I just had to change the !facingRight to facingRight. idk why but i think it might be referring to the character facing instead of the enemy. Not sure what the deal is but I got it working. Thank you so much Fishman for your patients and understanding and I apologize for the noobish and uneducated questions and for you putting up with my cluelessness. You guys on the Unity forums are awesome have a great night brotha!!