- Home /
Tracking Vertical Angle between Camera and Object
Hi there,
So i have a static Object in my scene. I want to keep track of the angle between the direction that the camera is looking in and the vector from the camera to the static object, both horizontally and vertically. I want to determine the angles every frame, because the camera is going to rotate a lot.
I'm able to successfully track the horizontal angle with the following code:
Vector3 TargetVector = TargetShape.transform.position - MainCamera.transform.position;
Vector3 TargetHorizontalVector = new Vector3(TargetVector.x, 0, TargetVector.z);
Vector3 CameraHorizontalVector = new Vector3(MainCamera.transform.forward.x, 0 , MainCamera.transform.forward.z);
float HorizontalAngle = Vector3.SignedAngle(CameraHorizontalVector, TargetHorizontalVector, MainCamera.transform.up);
This way the horizontal angle between the Camera forward direction and the object is always correct, no matter how much I rotate the camera in X or Y direction. If rotate the camera up or down, the horizontal angle doesn't change, if I rotate it left or right, the angle changes respectively.
However if I try to do the same thing for the vertical angle with the following code:
Vector3 TargetVector = TargetShape.transform.position - MainCamera.transform.position;
Vector3 TargetVerticalVector = new Vector3(0, TargetVector.y, TargetVector.z);
Vector3 CameraVerticalVector = new Vector3(0, MainCamera.transform.forward.y, MainCamera.transform.forward.z);
float VerticalAngle = Vector3.SignedAngle(CameraVerticalVector, TargetVerticalVector, MainCamera.transform.right) ;
Now when i rotate the camera up and down, the vertical angle changes respectively. However when i rotate the camera left and right, the vertical angle also changes in weird pattern (kind of looks like a hyperbola). When i rotate the camera left and right, I want the vertical angle to not change at all.
How could i change my solution so that i wouldn't get this change in my vertical angle measurement, when rotating the camera left and right (so around the y axis)?