Having trouble finding angle of the object.

I’ve been trying to get this code to work for an object to draw a line to the player based on the players current location. This script is going to be used for the enemyAi to follow the player so I’m going to use dir (which is the angle that the object is looking at) and then use the translate the object by using the Sin(dir) * spd; and the Cos(dir) * spd;

My Code:

dir =Mathf.Deg2Rad * Vector3.Angle(player.transform.position - transform.position,Vector3.forward);
Debug.DrawRay(transform.position,new Vector3(Mathf.Sin(dir),0,Mathf.Cos(dir))*sightRange);

//To move the enemy object
amountToMove.x = Mathf.Sin(dir)*spd*Time.deltaTime;
amountToMove.z = Mathf.Cos(dir)*spd*Time.deltaTime;

But for some reason it either doesn’t work and points in a different direction or only works at certain spots.

Any reasons why this is happening?

Angles in 3D space take more thought than angles in 2D space. You have to ask, “angle relative to what?” In addition angles you get back are unsigned. You have to provide a reference and some additional code to get a signed angle.

Typically the kind of problem you are outlining (drawing a line between points), is handled by vectors. If you outline how you are drawing lines, then it is likely we can give you a simple solution that avoid complicated angle calculations.

Given what I can see of your code, if you need to plow ahead with angles, take a look at Mathf.Atan2().