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.
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.
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:-
var enemyPos: Vector3 = transform.InverseTransformPoint(enemy.position);
enemyPos.y = 0.0;
(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:-
enemyPos.Normalize();
var screenVec: Vector2 = new Vector2(enemyPos.x, enemyPos.z);