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 /
  • Help Room /
avatar image
0
Question by misanthropowitsch · Oct 18, 2016 at 04:27 PM · enemytargeting

Homing Missile targetting the nearest Enemy

Hello,

I made a script, with a Homing Missile in Unity2D. Game is a Sidescrolling Platformer Contrastyle.

The missile, which is fired from a gun muzzle is doing it´s job. However.. It doesn´t recognize, which enemy is currently the nearest Target. I tried to google that. I also found an answer in the forums, but it is using Linq. Since I have absolutely no clue about Linq, is there another solution I could use?

Currently I am using "FindGameObjectWithTag to find the target for the missile. I also know, that I somehow have to make it work that, so that the missile recognizes a certain distance to the nearest enemy, but I don´t get, how to properly set it up.

Do I have to use an Array for that?

Another solution could be, to make the missile just allow to search for a target, if it is visible on the screen? However, my recent trys with this were a desaster.

Help or a hint would be much appreciated, since at the moment if I am direclty in front of the enemy the missile is flying on to the next target like 2 screens away.

Thanks a lot.

Here´s the script.

 public GameObject target;

 Rigidbody2D rb;

 


 // Use this for initialization
 void Start () {


 }

 // Update is called once per frame
 void FixedUpdate () {

     rb = GetComponent<Rigidbody2D>();
     if(target = GameObject.FindGameObjectWithTag ("Enemy"))
     {

         Vector2 pointToTarget = (Vector2)transform.position-(Vector2)target.transform.position;

         pointToTarget.Normalize ();

         float value = Vector3.Cross(pointToTarget, transform.right).z;

         if(value >0) 

         {
             rb.angularVelocity = rotatingSpeed;
         }
         else if (value < 0)
             rb.angularVelocity = -rotatingSpeed;           

         else
         rb.angularVelocity = 0; 
     }

 }



 
 

 
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
2

Answer by OutOfRam · Oct 18, 2016 at 11:16 PM

There is no builtin method for finding the closest enemy, but there is a pretty simple way to code it. add this function to your script and it will return the nearest GameObject with the tag.

     GameObject FindClosestByTag(string tag)
     {
         GameObject[] gos;
         gos = GameObject.FindGameObjectsWithTag(tag);
         GameObject closest = null;
         float distance = Mathf.Infinity;
         Vector3 position = transform.position;
         foreach (GameObject go in gos)
         {
             Vector3 diff = go.transform.position - position;
             float curDistance = diff.sqrMagnitude;
             if (curDistance < distance)
             {
                 closest = go;
                 distance = curDistance;
             }
         }
         return closest;
     } 

Essentially the function grabs all objects with the tag 'tag' and individually compares the distance between them returning the closest one.

I hope this helps!

Comment
Add comment · Show 1 · 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 misanthropowitsch · Oct 19, 2016 at 01:02 AM 0
Share

Thanks for your answer and help!

I feel like I´m on the right way. I get an error though. It made the most sense to me, to put the function into void Start.

As soon as I hit the $$anonymous$$ey to Instantiate the "missile" I get an error stating:

The variable target (or whatever I´d call it) has not been assigned.

Tried a lot at the moment. How do I assign the variable correctly? and sorry, if this is something really noobish. I just don´t get, why the target is not found.

This is, how it is currently looking. I had to change tag to Enemy after string didn´t I?

     public GameObject gos; //target before

 Rigidbody2D rb;

 



 // Use this for initialization
 void Start () {
 }
     GameObject FindClosestByTag(string Enemy) // changed from former tag to Enemy

     {
         GameObject[] gos;
         gos = GameObject.FindGameObjectsWithTag("Enemy");
         GameObject closest = null;
         float distance = $$anonymous$$athf.Infinity;
         Vector3 position = transform.position;
         foreach(GameObject go in gos)
         {
             Vector3 diff = go.transform.position - position;
             float curDistance = diff.sqr$$anonymous$$agnitude;
             if(curDistance < distance)
             {
                 closest = go;
                 distance = curDistance;

             }
         }
         return closest;
     }



 // Update is called once per frame
 void FixedUpdate () {

     rb = GetComponent<Rigidbody2D>();


         



         Vector2 pointToTarget = (Vector2)transform.position-(Vector2)gos.transform.position; //target before

         pointToTarget.Normalize ();

         float value = Vector3.Cross(pointToTarget, transform.right).z;

         if(value >0) 

         {
             rb.angularVelocity = rotatingSpeed;
         }
         else if (value < 0)
             rb.angularVelocity = -rotatingSpeed;          
         else
         rb.angularVelocity = 0; 
         
     }

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

Character continues moving when locked onto an enemy 1 Answer

Attack timer stops after killing enemy (when attack script loose target) 1 Answer

Switching Target 0 Answers

Basic Enemy follow script for Unity five, desperately needed! 0 Answers

Enemies cannot kill Player. 0 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