Search Unity

Arrows on HUD and Distance to Target HELP!

Discussion in 'Scripting' started by pixelone, Sep 9, 2012.

  1. pixelone

    pixelone

    Joined:
    Apr 16, 2010
    Posts:
    157
    I found this little gem in the Unity docs.

    Code (csharp):
    1. / Print the name of the closest enemy
    2. print(FindClosestEnemy().name);
    3.  
    4. // Find the name of the closest enemy
    5. function FindClosestEnemy () : GameObject {
    6.     // Find all game objects with tag Enemy
    7.     var gos : GameObject[];
    8.     gos = GameObject.FindGameObjectsWithTag("Enemy");
    9.     var closest : GameObject;
    10.     var distance = Mathf.Infinity;
    11.     var position = transform.position;
    12.     // Iterate through them and find the closest one
    13.     for (var go : GameObject in gos)  {
    14.         var diff = (go.transform.position - position);
    15.         var curDistance = diff.sqrMagnitude;
    16.         if (curDistance < distance) {
    17.             closest = go;
    18.             distance = curDistance;
    19.         }
    20.     }
    21.     return closest;    
    22. }
    How do I display a distance counter to target. I have the target tagged as "Goal" and I want to show how far I am away in distance from the goal and as I move towards it or away the counter goes down or up. Also, how do I show arrows on the HUD to tell where enemies are. Enemies are tagged "Enemy". Thank you Just need some help or point me in the right direction.
     
  2. cat_ninja

    cat_ninja

    Joined:
    Jul 14, 2010
    Posts:
    197
    Well to show the distance between you and the closest enemy do

    function UpdateCounter ()
    {
    Array enemies = gameObject.FindGameObjectsWithTag("Enemy")
    Transform closest;
    float bestScore;
    foreach(Transform e in enemies)
    if(Vector3.Distance(transform.position,e.position) < bestScore)
    closest = e;

    //This you set yourself (Create other -> GUI Text) then just make it a variable
    GUITEXT.text = "Distance to enemy: "+Vector3.Distance(transform.position,closest.position)
    }

    Sorry I don't know how to do scripts in the forums. This should help though. You may not want to call this every frame because they way I wrote it is pretty slow, but if you update it like every 4-10 frames it should be fine. The HUD telling you where enemies are requires a minimap, I've never done one so I don't have the code memerized, but ask around or just try it yourself. Hope this helps :D
     
  3. pixelone

    pixelone

    Joined:
    Apr 16, 2010
    Posts:
    157
    @Cat_ninja - Thanks a bunch. I will give this a shot.