# Arrows pointing to offscreen enemy

Hi guys, I’m looking for a good tutorial for how to create arrows that point in the direction of a target offscreen. The arrows would be 2D gui, pointing to 3D objects, and sit just near the edge of the screen.

Is there a tutorial for this, because I think the maths would make my head explode!

I think what I need to do is draw a line to the enemy, and then detect where it touches the edge of the screen, and place my arrow there. But I’m not sure how to do that without complicated mathematics!

You can use the builtin camera methods to get screen point and viewport point, both could be useful depending on the desired outcome, my example uses viewport as it tends to be easier to work with (as it’s always between (0, 0) (bottom left) and (1, 1) (top right).

Vector3 screenPos;
Vector2 onScreenPos;
float max;
Camera camera;

void Start(){
camera = Camera.main;
}

void Update () {
screenPos = camera.WorldToViewportPoint(transform.position); //get viewport positions

if(screenPos.x >= 0 && screenPos.x <= 1 && screenPos.y >= 0 && screenPos.y <= 1){
Debug.Log("already on screen, don't bother with the rest!");
return;
}

onScreenPos = new Vector2(screenPos.x-0.5f, screenPos.y-0.5f)*2; //2D version, new mapping
max = Mathf.Max(Mathf.Abs(onScreenPos.x), Mathf.Abs(onScreenPos.y)); //get largest offset
onScreenPos = (onScreenPos/(max*2))+new Vector2(0.5f, 0.5f); //undo mapping
Debug.Log(onScreenPos);
}

Hello,

I just used the code above and it works perfectly fine to me. My problem is, I don’t understand, why it works …especially this line:

onScreenPos = new Vector2(screenPos.x-0.5f, screenPos.y-0.5f)*2; //2D version, new mapping

I tried and tested and made some changes and it turned out it has to be done this way, but since screenPos can have any value, depending on where related to transform.position the viewport currntly is, I don’t see how it can work.