Search Unity

player tracking and following enemy then attacking.

Discussion in 'Scripting' started by shadow-river, Jul 27, 2014.

  1. shadow-river

    shadow-river

    Joined:
    May 29, 2013
    Posts:
    63
    I'm making an rts game and i'm having a little trouble with the player mechanics.
    I'm using unity navmesh for movement with ray-casting and so far its working grate.
    so far I have goten the enemy AI working perfectly were the enemy choses a random target using an array then follows and attacks when the distance is close enough.

    I'm able to move my player ships around the map by left clicking to select then right clicking to move to a spot on the navmesh (this part works fine) the problem is that I'm wanting to right click on an enemy, and the player ship that I've selected will follow the enemy and when he's close enough he will attack.

    I have looked at my code so much that its hard to see now lol.
    I was wondering if anyone could point me in the right direction.

    the player ship locks on to the game object that I have loaded into a variable by ray-casting and tag finding but doesn't follow. it loads properly but the player ship ends up going to the place that the enemy was.(the object does load into the variable properly)
    and when I want the ship to auto fire it only does by Onmouse down ( I know I have it in the Onmouse down
    if-statement but if I put it else were it doesn't work at all. also the player ship doesn't tern towards the enemy when firing either.
    sorry if my explanation is a little to vague.

    heres my code . if any one can help thanks and also sorry I know my spellings bad.

    Code (JavaScript):
    1. #pragma strict
    2. //auto attack/track if within distance
    3. var object;
    4. var distance : float = 10.0;
    5.  
    6. //controls state changes
    7. var sw : int = 0;
    8.  
    9.  
    10. //Navagation mesh components
    11. var navComponent : NavMeshAgent;
    12.  
    13. //HPBAR
    14. var playerHpBar : GUITexture;
    15. var phpcurrent : float = 100.0;
    16. var phpmax : float = 100.0;
    17. var percent : int = 20;
    18. var dam : int = 10;
    19.  
    20. //efects for attack and destroy stuff
    21. var BeemAttackPrefab : GameObject;
    22. var Beem : AudioClip;
    23. var Expl : GameObject;
    24.  
    25. //attack timer controll
    26. var attackTimer : float;
    27. var coolDown : float;
    28.  
    29. //raycasting
    30. var hit1 : RaycastHit;
    31.  
    32. function Start () {
    33. navComponent = this.transform.GetComponent(NavMeshAgent);
    34. }
    35.  
    36. function Update () {
    37. //HPBar controll
    38. var percentofhp = phpcurrent/phpmax;
    39. var hpBarLength = percentofhp*percent;
    40.  
    41. playerHpBar.guiTexture.pixelInset.width = hpBarLength;
    42.  
    43. if(phpcurrent <= 0)
    44. {
    45.     phpcurrent = 0;
    46.     Explosion();
    47. }
    48.  
    49. //Attack cool down controle
    50. if(attackTimer > 0)
    51.         attackTimer -= Time.deltaTime;
    52.     if(attackTimer < 0)
    53.     {
    54.         attackTimer = 0;
    55.     }  
    56.  
    57. switch(sw)
    58.     {
    59.         case 1:
    60.                 if(Input.GetMouseButtonDown(0))
    61.                     {
    62.                         sw = 0;
    63.                     }
    64.                  
    65.                     if(Input.GetMouseButtonDown(1))
    66.                     {
    67.  
    68.                         var ray1 = Camera.main.ScreenPointToRay(Input.mousePosition);
    69.                         var hit1 : RaycastHit;
    70.                         if(Physics.Raycast(ray1, hit1, 100))
    71.                      if(hit1.collider.tag == "en")
    72.                      {
    73.                                        
    74.                     var object = hit1.transform.gameObject;
    75.                     distance = Vector3.Distance(hit1.transform.position, transform.position);
    76.                     var dir : Vector3 = (hit1.transform.position - transform.position).normalized;
    77.                      var direction = Vector3.Dot (dir,transform.forward);
    78.                     print ("object hit!");
    79.                      
    80.                       if(distance <= 5.0) // && direction > 0.8)
    81.                     {
    82.                         sw=2;
    83.                      
    84.                      }
    85.                    
    86.                     else      
    87.                     {
    88.                         navComponent.enabled = true;
    89.                         navComponent.SetDestination(hit1.transform.position);
    90.                      
    91.                     }
    92.          
    93.     }
    94.     else
    95.     {
    96.         navComponent.enabled = true;
    97.         navComponent.SetDestination(hit1.point);
    98.     }
    99.  
    100.     }
    101.      
    102.          break;
    103.      
    104.         case 2:  
    105.          
    106.            
    107.              if(distance <= 5.0)// && direction > 0.8)
    108.                     {
    109.                         navComponent.enabled = true;
    110.                         transform.LookAt(hit1.transform);
    111.                  
    112.                      
    113.                         if(attackTimer == 0)
    114.                      {
    115.                         attackTimer = coolDown;
    116.                          attackFire ();
    117.                      }
    118.                                                  
    119.                      }
    120.                      else
    121.                    
    122.                      {
    123.                          navComponent.SetDestination(hit1.transform.position);
    124.                           //if(Input.GetMouseButtonDown(1))
    125.                           //{
    126.                           //    sw = 1;
    127.                           }              
    128.  
    129.         break;
    130.        
    131.      
    132.     }
    133.     }
    134.  
    135. function OnTriggerEnter(other:Collider)
    136. {
    137.  
    138.     if(other.tag == "Beem2")
    139. {
    140.     this.phpcurrent -= dam;
    141.     Destroy(other.gameObject);
    142. }
    143.  
    144.  
    145. }
    146.  
    147.  
    148. function OnMouseUp (){
    149.  
    150.         sw = 1;
    151.      
    152.     }      
    153. function attackFire () {
    154.     transform.LookAt(hit1.transform);
    155.     Instantiate(BeemAttackPrefab,this.transform.position,this.transform.rotation);
    156.     audio.PlayOneShot(Beem);
    157.  
    158. }
    159.  
    160. function Explosion (){
    161. var Explo : GameObject = Instantiate(Expl, transform.position, transform.rotation);
    162. Destroy (this.gameObject);
    163. }
    164.  
    165. @script RequireComponent(AudioSource)      
    166.              
    167.          
    168.  
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    ok, first impressions:

    You're trying to cram everything into one script.... unity is a component system, break things down into distinct "things". For example, the healthbar has nothing to do with movement, firing etc. so that should be in it's own script where it only concerns itself with what it specifically does.

    Your code is a little tricky to follow, some of that is the "everything" in one place, some of it is layout. Try to keep a consistent use of {} and indentation. It might seem trivial but it helps to keep things clean.

    Comments... use them, for example in your switch, you have 0, 1, 2... ok, that works but what are those states in "fluffy english (or whatever) language"? if you want others to understand your code (or intentions behind the code), or more importantly if you come back to the code a few months later you don't want to have to trawl through the entire thing figuring out what you did. :)

    As to the specific issues,
    Code (csharp):
    1. navComponent.SetDestination(hit1.point);
    you are setting the the navmeshagent to head to the point where you clicked. If you want to "follow" a target you going to need to check outside of the mousebutton if statements to see if there is a target (I think you've called it object?) and if there is set the destination to the target's location. With the autofire, you need to get the shooting code out of the mousebutton ifs and into it's own (or possibly as a nested if in the suggested "follow" if to save checking for the target existing twice). You could even go as far and splitting the "handle input" and "move/follow/fire" into seperate scripts (you'll need a targetObject and a targetVector3 to handle being sent to a point in space and follwing a target object if you do that).

    pseudocode
    Code (csharp):
    1.  
    2. if(mousebutton0)
    3. {
    4.     ...
    5. }
    6. if(mousebutton1)
    7. {
    8.     ...
    9. }
    10. ---- another script? ----
    11. if(target exists)
    12. {
    13.     setDestination(target location)
    14.     if(close enough to fire)
    15.     {
    16.         fire
    17.     }
    18. }
    19.  
     
  3. shadow-river

    shadow-river

    Joined:
    May 29, 2013
    Posts:
    63
    thanks for your reply and you are right, I figured that out before you replied. I changed it to this and it worked.
    I do plan on cleaning up my code and I will for any that I plan to post. (thanks for your advice I do realize it was a bit messy i'm still learning lol)

    Code (JavaScript):
    1. var ray1 = Camera.main.ScreenPointToRay(Input.mousePosition);
    2.                         var hit1 : RaycastHit;
    3.  
    4. switch(sw)
    5.     {
    6.         case 1:
    7.        
    8.                 if(Input.GetMouseButtonDown(0))
    9.                     {
    10.                         sw = 0;
    11.                     }
    12.                  
    13.                     if(Input.GetMouseButtonDown(1))
    14.                  
    15.                      if(Physics.Raycast(ray1, hit1, 100))
    16.                     {
    17.                     if(hit1.collider.tag == "en")
    18.                
    19.                     {
    20.                    
    21.                       object = hit1.collider.gameObject;
    22.                         sw=2;
    23.                  
    24.                     }
    25.  
    26.                        else
    27.                     {
    28.                         navComponent.enabled = true;
    29.                         navComponent.SetDestination(hit1.point);
    30.                     }
    31.                  
    32.     }
    33.  
    34.         break;
    35.      
    36.         case 2:  
    37.          
    38.            
    39.                  
    40.                
    41.                     distance = Vector3.Distance(object.transform.position, transform.position);
    42.                     var     dir : Vector3 = (object.transform.position - transform.position).normalized;
    43.                        direction = Vector3.Dot (dir,transform.forward);
    44.                  
    45.                     ob=true;
    46.                  
    47.      
    48.  
    49.             if(distance <= 5.0 && (ob ))
    50.                     {
    51.                         transform.LookAt(object.transform);
    52.                         navComponent.enabled = false;
    53.                
    54.                      
    55.                         if(attackTimer == 0)
    56.                      {
    57.                         attackTimer = coolDown;
    58.                          attackFire ();
    59.                      }
    60.      
    61.                      
    62.                    
    63.                      }
    64.                    
    65.                      if(distance >= 5.0 && (ob ))
    66.                      {
    67.                          navComponent.enabled = true;
    68.                          navComponent.SetDestination(object.transform.position);
    69.                        
    70.                       }
    71.                  
    72.                  
    73.          
    74.    
    75.                  
    76.  
    77.         break;
    78.  
    79.    
    80.      
    81.     }