Search Unity

An icon pointing to an offscreen enemy?

Discussion in 'Scripting' started by cj-currie, Oct 13, 2009.

  1. cj-currie

    cj-currie

    Joined:
    Nov 27, 2008
    Posts:
    337
    Hey, all,

    I'm pretty experienced with Unity's scripting API, but here I am presented with a problem that baffles my grasp of scripting.

    I need to find a way to display at the edge of the screen GUI icons that point toward nearby targets. I have the mechanics for target finding working and I understand how Vector3.Angle() works, but I have no idea how to translate relative position into screen coordinates. The targets will be all around the player, above, below, and behind, and the arrow icons should do something like this Microsoft classic:


    Observe the arrow at the right side of the screen. You get the point.

    Any advice or ideas in the right direction would be great. So far I'm using a Vector3.Angle() calculation to see if the target is behind the camera, then the difference in global global position to get a vector pointing at the target, but I don't know how to translate that to screen coords.

    Thanks in advance!
     
  2. sebako

    sebako

    Joined:
    Jun 27, 2009
    Posts:
    301
    You mean like a bounding box in the good old command conquer when select a unit? If so I got the same problem, someone give me a hint using bounds and the line renderer to draw the box around the characters, but I cannot figure out how.
     
  3. andeeeee

    andeeeee

    Joined:
    Jul 19, 2005
    Posts:
    8,768
    First thing to note is that Vector3.Angle gives the angle in 3D space. If the enemy can be above or below the plane of the player then it will not return the correct heading. Start by getting the enemy's position in the player's coordinate space:-
    Code (csharp):
    1. var enemyPos: Vector3 = transform.InverseTransformPoint(enemy.position);
    2. enemyPos.y = 0.0;
    3.  
    (You also need to set the point's Y coordinate to zero to get the heading vector that ignores the up/down position of the enemy.) You can use Vector3.Angle to get the heading angle with Vector3.forward if you need to rotate a GUI element. However, if a Vector2 is more useful, just normalise the heading vector and make a new Vector2 using its X and Z values:-
    Code (csharp):
    1. enemyPos.Normalize();
    2. var screenVec: Vector2 = new Vector2(enemyPos.x, enemyPos.z);
     
  4. Muckel

    Muckel

    Joined:
    Mar 26, 2009
    Posts:
    471
    Hello,
    plz can you show me some example code how to get Vector3.Angel ??
    many thanks...
    :oops: kerstin
     
  5. andeeeee

    andeeeee

    Joined:
    Jul 19, 2005
    Posts:
    8,768
    The doc page for Vector3.Angle has an example script that essentially does what I've described.