I'm working on a top-down 3D game where things spawn off camera. Movement only occurs on 2 axis (x and z). Rotation is about y axis.

The player is in the center of the camera and needs to have indicators at the edge of the screen to show where the item is relative to the players location.

I've managed to figure out the distance from my player to the target just using the distance between 2 Vector3 points.

However, I can't figure out how to translate this into a direction/angle for an indicator arrow that I have instantiated as a child of the canvas UI and make it point to the edge of the screen.


use the arctangent to find the angle

angle = atan((z2-z1)/(x2-x1));

the angle will likely be in radians, but it will depend on the implementation of the arctangent function.

because of the period of the arctangent function, you will need to adjust it based on the quadrant of p2 with respect to the origin (p1). Here is a simple way to do it:

angle = atan((z2-z1)/(x2-x1));
if (x2 < x1) angle += pi;

this will result in an angle in the range [-pi/2, 3*pi/2) radians. if you need it from [0, 2*pi), then just add:

if (angle < 0) angle += 2*pi;


I forgot to mention the special case where x1 == x2. In this case, hardcode the angles to avoid division by 0.

if (x1 == x2)
    angle = (z1 < z2) ? pi/2 : -pi/2;
    // see formula above

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.