Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Direisnecro · Dec 09, 2015 at 09:48 AM · javascriptarrayfor-loopartificial intelligencetower-defense

Tower defense, turret aiming wrong.

So, im making a TD game, and im trying to make the turret shoot at the closest enemy in a sphere collider, but instead it just shoots at the newest enemy to enter the sphere collider attached to the turret

Heres the code, mind you i havent added in little things like checking if the turret has a target yet and whatnot, mostly because ive been stuck on this for about a day and a half :\

 var Target : GameObject;
 var TargetList = new Array();
 var DistanceVector : Vector3;
 var TargetPos : Vector3;
 var TurretPos : Vector3;
 var ShortestDistance : float = 9999;
 var Distance : float;
 
 function Start () 
 {
 TurretPos = transform.position;
 }
 
 function Update () 
 {
     
     FindEnemy();
     transform.LookAt(Target.transform.position);
 }
 
 function OnTriggerEnter (col : Collider)
 {
     if (col.gameObject.tag == "Enemy")
     {    
             TargetList.Add(col.gameObject);
     }
 
 
 }
 function OnTriggerExit (col : Collider)
 {
     if (col.gameObject.tag == "Enemy")
     {    
             TargetList.Remove(col.gameObject);
     }
 
 
 }
 function FindEnemy()
 {
     for(i=0;i<TargetList.length;i++)
     {
 
         TargetPos = TargetList[i].gameObject.transform.position;
         DistanceVector = TargetPos - TurretPos;
         Distance = DistanceVector.magnitude;
         if(Distance < ShortestDistance)
         {
                 Target = TargetList[i].gameObject;
             ShortestDistance = TargetPos.magnitude;
             
         }
         
     }
 }
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by wibble82 · Dec 09, 2015 at 11:01 AM

Hey

There's a little bug on line 50: ShortestDistance = TargetPos.magnitude;

Which should be: ShortestDistance = Distance;

Also worth noting you've got a lot of variables there that are member variables but could just be local variables. For example: TargetPos, DistanceVector, Distance and ShortestDistance are only used inside FindEnemy. TurretPos is also just a copy of transform.position.

I'd be tempted to remove those variables from the class definition and just have something like:

 function FindEnemy()
 {
     var shortest_distance : float = float.MaxValue;
 
     for(i=0;i<TargetList.length;i++)
     {
          var offset : Vector3;
         var target_pos : Vector3;
         var distance : float;
 
          target_pos = TargetList[i].gameObject.transform.position;
          offset = target_pos - transform.position;
          distance = offset.magnitude;
          if(distance < shortest_distance)
          {
             Target = TargetList[i].gameObject;
             shortest_distance = distance;            
          }
          
      }
  }

Basically minimizing my use of shared variables or duplication of data. Trying to stick to those rules really helps minimize bugs.

-Chris

Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Direisnecro · Dec 09, 2015 at 10:28 PM 0
Share

thank you, it works cleaner now, but unfortunetly im not sure how to get the result i want, it will stick to a single target until it kills it, and Then it will find the closest, i want it to always shoot the closest target no matter what.

I also have a bug where if two turrets are targetting the same enemy and it dies, the turret that Did not kill the enemy will stop ai$$anonymous$$g and shooting and will spit this bug : $$anonymous$$issingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.

i attempted to fix it with Targetlist.Remove in the shoot function:

 function Shoot()
 {    
     Debug.Log("I shot");
     Target.GetComponent("Pathfinding").ApplyDamage(5);
     if(Target.GetComponent("Pathfinding").Health <= 0)
     {
         Destroy(Target.gameObject);
         TargetList.Remove(Target.gameObject);
         Target = null;
     }
 }

but alas that does not work

avatar image wibble82 Direisnecro · Dec 10, 2015 at 03:10 PM 0
Share

Hmmm. Assu$$anonymous$$g you have taken my code exactly as I wrote it, and you are still calling 'FindEnemy' every frame (from Update), it should always get the closest one. Would you like to just post your updated code here or in your original question so we can see the whole thing.

-Chris

avatar image Direisnecro · Dec 11, 2015 at 09:12 PM 0
Share

This is the code im using currently

 var Damage : int = 5;
 var ShootTime : float = 1.0;
 var Target : GameObject;
 var TargetList = new Array();
 var Timer : float;
 
 function Start () 
 {
     TurretPos = transform.position;
 }
 
 function Update () 
 {
     Timer += Time.deltaTime;
     if(Target == null)
     {
         TargetList.remove(Target);
     
     }
     
     FindEnemy();
     
     if(Target)
     {        
         transform.LookAt(Target.transform.position);
         if(Timer >= ShootTime)
         {
             Shoot();
             Timer = 0;
         }
     
     }
 }
 
 function OnTriggerEnter (col : Collider)
 {
     if (col.gameObject.tag == "Enemy")
     {    
             TargetList.Add(col.gameObject);
     }
 }
 function OnTriggerExit (col : Collider)
 {
     if (col.gameObject.tag == "Enemy")
     {    
             TargetList.Remove(col.gameObject);
     }
 }
 
 function Shoot()
 {    
     Debug.Log("I shot");
     Target.Send$$anonymous$$essage("ApplyDamage",Damage);
     
 }
 
  function FindEnemy()
  {
      var shortest_distance : float = float.$$anonymous$$axValue;
      
      for(i=0;i<TargetList.length;i++)
      {
           var offset : Vector3;
          var target_pos : Vector3;
          var distance : float;
  
           target_pos = TargetList[i].gameObject.transform.position;
           offset = target_pos - transform.position;
           distance = offset.magnitude;
           if(distance < shortest_distance)
           {
              Target = TargetList[i].gameObject;
              shortest_distance = distance;            
           }
           
       }
   }
 



And its kinda working, but i get an $$anonymous$$issingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.

and i tried to fix it with:

 if(Target == null)
         {
             TargetList.remove(Target);
         
         }

But every now and again it still happends, and the turret will ignore all enemies that were in its range when another tower killed its target until a new enemy hits the collider

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Turn all objects in the array to make same thing 0 Answers

"For"-Loop only works for final element in array 1 Answer

Array index is out of range 1 Answer

have array target person of most priority/stick with top prior 0 Answers

Making an Array of Animations Play at Random With No Repeats 3 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges