Calculate Angle: From & To

Hello,

I’m trying to find what the angle is between my helicopter, and a target.

Example:

Helicopter is facing North, and the target is East of the helicopter, thus the angle is 90 degrees. I don’t want to take into account the targets angle, only the targets position related to the helicopters angle.

Also, I don’t want to include the Y position of both the helicopter and target, as both may be at different heights

I have this, but I don’t know if the maths/formula is correct:

``````var angleBetween = Quaternion.Angle(transform.rotation, Quaternion.LookRotation(target.position - transform.position));
``````

I’ve included a rather complicated illustration:

You could do something like this, using trigonometry:

Vector3 toTarget = (target.transform.position - transform.position).Normalize();

Vector3 forward = transform.forward;

float angle = Mathf.Acos(Vector3.Dot(toTarget, forward));

But I’m sure there are more efficient ways of calculating it.

Quaternion.Angle() and Vector3.Angle() give you back an unsigned angle. So you will need to figure out if the object is to the left or right of the helicopter. There are several posts with different solutions for figuring out if an object is to the left or right. Here is one:

Your second problem is one you mention, the ‘Y’ height. Quaternion.Angle() and Vector3.Angle() will calculate the angle in 3D space. The typical way to solve this is to modify the vectors to remove ‘Y’ (and use Vector3.Angle()). So your angle would be something like:

``````Vector3 v3A = target.position - transform.position;
v3A.y = 0;
Vector3 v3B = transform.forward;
v3B.y = 0;
float angle = Vector3.Angle(v3A, v3B);
``````

An alternate, you can approach this problem as a 2D rotation, and use Atan2().

``````Vector3 v3A = target.position - transform.position;
float angle1 = Mathf.Atan2(v3A.z, v3A.x);
float angle2 = Mathf.Atan2(transform.forward.z, transform.forward.x);
float angle = Mathf.DeltaAngle(angle1, angle2);
``````

This is what I use, but it only gives 0 to 180, 0 being directly in front 180 being directly behind so 90 is both right and left, but I’m sure you can work out if the target is on it’s right or left.

I only use it to allow the weapons to fire if within a certain angle.

``````var enemy : Transform;

private var targetDir : Vector3;
private var forward : Vector3;
private var targetAngle : float;

function Update(){

targetDir = enemy.position - transform.position;
forward = transform.forward;
targetAngle = Vector3.Angle(targetDir, forward);
}
``````