# Find angle to target (not angle to rotate by)

I am trying to find the angle to a target. However, all the solutions I am finding in the Unity community are to find the angle for rotating towards a target.
I.e.

In the above solutions if you start turning towards the target the angle will decrease, where the player and target are stationary in position.

A 2d arrow is what I am after, as exampled in the GUI2d arrow above. I want my angle to be a true angle of the target position in relation to the player. I.e. if the target is above the player then the angle would be 0, to the right then 90, below then 180 or the left then 270 of where the player is facing. Rotation should not matter, only position.

I would appreciate any help.

exact same problem as this question about the angle of a mouse cursor. In that case the math I gave used the standard mathematical angles, 0 being right and increasing counter-clockwise, but it can be switched to up as 0 and increasing clockwise by just swapping x and y when you call Atan2.

I was able to get a rotable GUI texture using the code in the below URL’s:

It seems to work pretty well.

myOffscreenIndicator is a game object with contains the RotatableGUIItem script.

``````					//Get the targets position on screen into a Vector3
Vector3 targetPos = Camera.current.WorldToScreenPoint (target.transform.position);
//Get the middle of the screen into a Vector3
Vector3 screenMiddle = new Vector3(Screen.width/2, Screen.height/2, 0);
//Compute the angle from screenMiddle to targetPos
float tarAngle = (Mathf.Atan2(targetPos.x-screenMiddle.x,Screen.height-targetPos.y-screenMiddle.y) * Mathf.Rad2Deg)+90;
if (tarAngle < 0) tarAngle +=360;

if(targetPos.z < 0) {
myOffscreenIndicator.GetComponent<RotatableGuiItem>().angle = -(tarAngle-90); //Quaternion.Euler(tarAngle,270,90);
borderPos.x = (Screen.width/2) - Mathf.Cos((tarAngle+180) * Mathf.Deg2Rad) * 100.0f;
borderPos.y = (Screen.height/2) + Mathf.Sin((tarAngle+180) * Mathf.Deg2Rad) * 100.0f;
}
else {
myOffscreenIndicator.GetComponent<RotatableGuiItem>().angle = -(tarAngle+90); //Quaternion.Euler(-tarAngle,90,270);
borderPos.x = (Screen.width/2) - Mathf.Cos((tarAngle) * Mathf.Deg2Rad) * 100.0f;
borderPos.y = (Screen.height/2) + Mathf.Sin((tarAngle) * Mathf.Deg2Rad) * 100.0f;
}

myOffscreenIndicator.transform.position = borderPos;
``````