Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 StriXBeat · Jun 23, 2014 at 11:02 PM · gameobjecttarget

Targeting nearest enemy !

Hi there ! Yeah so, after quite 2 days of searching testing etc... I don't figure it out on what to do for targeting my player on the nearest enemy. I tried to pick up code for another question, testing etc... nothing :/ Here's my code, a bit messy sorry ! #pragma strict

 var distance : int;
 var lookAtDistance = 5;
 var target : GameObject;
 var targets : GameObject;
 var damping = 6.0;
 var fireSpeed : float = 15;
 private var waitTillNextFire : float = 0;
 private var canShoot : boolean = false;
 
 var bullet : GameObject;
 var bulletSpawn : GameObject;
 var bulletSound : GameObject;
 var muzzleFlash : GameObject;
 
 var reloading : boolean = false;
 var reloadingAnim : Animation;
 var reloadingAnimString : String;
 var reloadingSound : AudioSource;
 
 var magSize : int = 15;
 var currentMag : int = 15;
 var maxExtraAmmo : int = 250;
 var currentExtraAmmo : int = 250;
 
 var bulletHudTexture : Texture;
 var ammoCountRect : Rect = Rect(25,25,50,25);
 var ammoStartX : int = 100;
 var ammoY : float = 25;
 var ammoSize : Vector2 = Vector2(10,31);
 var ammoSpacing : float = 4;
 var ammoHudTexture : Texture;
 var ammoHudRect : Rect = Rect(25,50,50,25);
 
 function Start ()
 {
     var targets = GameObject.FindGameObjectsWithTag("Enemy");
     Debug.Log("number of enemies found: "+targets.length);
 }
 
 
 function Update () 
 {
     
         if(target != null)
         {
             Aiming();
         }
         else
         {
             canShoot = false;
             GameObject.Find("player").GetComponent(playerMovement).enabled = true;
             Debug.Log("Toast");
         }
 
     
     if(!reloading && Input.GetButtonDown("Reload") && currentMag < magSize && currentExtraAmmo > 0)
     {
         reloading = true;
         reloadingAnim.Play(reloadingAnimString);
         reloadingSound.Play();
     }
     if(!reloading && Input.GetButtonDown("Fire1")  && currentMag == 0 && currentExtraAmmo > 0)
     {
         reloading = true;
         reloadingAnim.Play(reloadingAnimString);
         reloadingSound.Play();
     }
     if(reloading && !reloadingAnim.IsPlaying(reloadingAnimString))
     {
         if(currentExtraAmmo >= magSize - currentMag)
         {
             currentExtraAmmo -= magSize - currentMag;
             currentMag = magSize;
         }
         if(currentExtraAmmo < magSize - currentMag)
         {
             currentMag += currentExtraAmmo;
             currentExtraAmmo = 0;
         }
         reloading = false;
     }
     
     if(currentMag > magSize)
         currentMag = magSize;
     if(currentExtraAmmo > maxExtraAmmo)
         currentExtraAmmo = maxExtraAmmo;
     if(currentMag < 0)
         currentMag = 0;
     if(currentExtraAmmo < 0)
         currentExtraAmmo = 0;
     
     var holdSound : GameObject;
     var holdMuzzleFlash : GameObject;
     
     if(Input.GetButtonDown("Fire1") && currentMag > 0 && !reloading && canShoot == true)
     {
         if(waitTillNextFire <= 0)
         {
             currentMag -= 1;
             if(bullet)
             {
                 Instantiate(bullet, bulletSpawn.transform.position, bulletSpawn.transform.rotation);
             }
             if(bulletSound)
             {
                 holdSound = Instantiate(bulletSound, bulletSpawn.transform.position, bulletSpawn.transform.rotation);
             }
             if(muzzleFlash)
             {
                 holdMuzzleFlash = Instantiate(muzzleFlash, bulletSpawn.transform.position, bulletSpawn.transform.rotation);
             }
             waitTillNextFire = 1;
         }
     }
     waitTillNextFire -= Time.deltaTime * fireSpeed;
     
     if(holdSound)
     {
         holdSound.transform.parent = transform;
     }
     if(holdMuzzleFlash)
     {
         holdMuzzleFlash.transform.parent = transform;
     }
     
 }
 
 function OnGUI ()
 {
 
     if(Input.GetKey(KeyCode.Tab))
     {
         for (var i : int = 1; i <= currentMag; i++)
         {
             GUI.DrawTexture(Rect(ammoStartX + ((i - 1) * (ammoSize.x + ammoSpacing)), ammoY, ammoSize.x, ammoSize.y), bulletHudTexture);
         }
         GUI.Label(ammoCountRect, currentExtraAmmo.ToString());
         GUI.DrawTexture(ammoHudRect, ammoHudTexture);
     }
 
 }
 function LookAt()
 {
         var rotation = Quaternion.LookRotation(target.transform.position - transform.position);
         transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
 }
 function Aiming()
 {
         for(var enemy : GameObject in targets)
         {
             distance = Vector3.Distance(enemy.transform.position, transform.position);
 
             if(Input.GetKey(KeyCode.Mouse1) && distance < lookAtDistance)
             {
                 target = enemy;
                    Debug.Log("My closest selected enemy so far is: "+target.transform.name);
                 LookAt();
                 canShoot = true;
                 GameObject.Find("player").GetComponent(playerMovement).enabled = false;
                 Debug.Log("Test");
             }
             else
             {
                 canShoot = false;
                 GameObject.Find("player").GetComponent(playerMovement).enabled = true;
                 Debug.Log("Toast");
             }    
            }
 }

Here's also topic that help me a little bit and where I pick up some line of code etc... I know that it's C# on the topic but I tried to rewrite it in javascript.

http://forum.unity3d.com/threads/select-target-from-nearest-enemy.8343/

thanks !

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 Jeff-Kesselman · Jun 23, 2014 at 11:05 PM

The distance between any two vectors A and B is the magnitude of the vector A-B

So, loop through all your enemies, subtract your position from their position and compare the magnitudes of the resulting vectors.

Comment
Add comment · Show 2 · 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 RafaelCN · Jun 23, 2014 at 11:22 PM 0
Share

You can do the distance between two vectors, supposing that we are working in two dimensions, we can do:

 distance = sqrt((pointA - pointA0)^2 + (pointB - pointB0)^2));

You can implement the calculus above and get the distance between a point A and B.

avatar image StriXBeat · Jun 24, 2014 at 09:34 AM 0
Share

Well, in my script I already had this

 function Ai$$anonymous$$g()
 {
         for(var enemy : GameObject in targets)
         {
             distance = Vector3.Distance(enemy.transform.position, transform.position);
 
             if(Input.Get$$anonymous$$ey($$anonymous$$eyCode.$$anonymous$$ouse1) && distance < lookAtDistance)
             {
                 target = enemy;
                    Debug.Log("$$anonymous$$y closest selected enemy so far is: "+target.transform.name);
                 LookAt();
                 canShoot = true;
                 GameObject.Find("player").GetComponent(player$$anonymous$$ovement).enabled = false;
                 Debug.Log("Test");
             }
             else
             {
                 canShoot = false;
                 GameObject.Find("player").GetComponent(player$$anonymous$$ovement).enabled = true;
                 Debug.Log("Toast");
             }    
            }
 }

It's not that ?

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

3 People are following this question.

avatar image avatar image avatar image

Related Questions

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

Using script's method from all of the gameobjects that has that script 2 Answers

How to create 3D game object in specified pixel size? 2 Answers

Unity3D Pressure Plate request. 3 Answers

Trying to delay movement of a GameObject 1 Answer


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