# Get Angle between camera and player with orbit camera

Hello,
I need a little help.
I have an orbital camera script that works fine.
To try to deal with ground collisions, I need to find the angle between the camera and the player.

Here is the code I tried :

``````Vector3 dir = _target.position - transform.position;
float angle = Vector3.Angle(_target.forward, dir);
Debug.Log(angle);
``````

It only works well when the camera is perfectly aligned with the player. Otherwise the values are not good.

I hope I managed to make myself understood … not easy.

“Angle between camera and player” is a bit ambiguous. Do you want the angle between camera forward vector and player forward vector? Do you want the angle between the player forward direction and the direction from the player to the camera? Can you elaborate on what you’re looking for or draw a picture maybe?

I’m sorry, I’m a little confused myself on what to ask.

Best if I show you the full code :

``````using UnityEngine;
using System.Collections;

public class CameraOrbit : MonoBehaviour
{
public Transform _target;

public float _distance = 9f;

public float _zoomStep = 1.0f;

public float _xSpeed = 4f;
public float _ySpeed = 2f;
public float yMinLimit = 20f;
public float yMaxLimit = 80f;
public float minDistance = 5;
public float maxDistance = 13;

private float _x = 0f;
private float _y = 0f;

private Vector3 _distanceVector;

void Start()
{
_distanceVector = new Vector3(0.0f, 0.0f, -_distance);

_x = 0;
_y = 30;

Rotate(_x, _y);
}

void LateUpdate()
{
if (_target)
{
CheckhitTerrain();

_x += Input.GetAxis("Mouse X") * _xSpeed;
_y += -Input.GetAxis("Mouse Y") * _ySpeed;
_y = ClampAngle(_y, yMinLimit, yMaxLimit);

Rotate(_x, _y);
}
}

private void CheckhitTerrain()
{
RaycastHit hit;
Ray ray = new Ray(transform.position+new Vector3(0, 10, 0), Vector3.down);
if (Physics.Raycast(ray, out hit, 10, layerMask))
{
yMinLimit = hit.point.y; // doesn't work because it is an angle not a point
_y = yMinLimit;
}
}

float ClampAngle(float angle, float min, float max)
{
if (angle < -360)
angle += 360;
if (angle > 360)
angle -= 360;
return Mathf.Clamp(angle, min, max);
}

void Rotate(float x, float y)
{
Quaternion rotation = Quaternion.Euler(y, x, 0.0f);
Vector3 position = rotation * _distanceVector + _target.position;

transform.rotation = rotation;
transform.position = position;
}
}
``````

In this code I need to calculate _y angle in the CheckhitTerrain() function,
so that I can raise my camera and not touch the ground.
I hope I was a little more understandable … sorry

Thanks