# Calculating angle to aim at target results in over/under aim depending on whether target is below/above

I'm calculating the angle (in radians, ranges -3.141 to 3.141 for yaw and -1.343 to 1.396 for pitch) to aim at in order to aim at a target position. The data I have is my local world camera position, and the world target position. The result should be the angle that needs to be set in order to aim precisely at the target.

This is a fairly simple calculation (even though I'm terrible at math) and it works without issue.. but it has a quirk when I'm in third person.

When I'm in first person, the "local world camera position" is effectively my player's eye position. When I'm in third person the "local world camera position" is effectively offset backwards and above from my player's eye position.

The quirk (actually a pretty big flaw right now) is that when the target position is elevated higher than my local world camera position, the result of my calculation results in an angle that over-shoots/over-aims the target. Inversely, when the target position is elevated lower than my local world camera position, the result of my calculation results in an angle that under-shoots/under-aims the target.

I've drawn this very bad sketch to try and explain my issue, for clarity my drawing is 2D and drawn from the side, but my application is 3D: http://i.imgur.com/qXvDnUZ.png

And to clear something up, the further my angle is pitched downwards, the closer my camera position will be to the top of my local player and the further my angle is pitched upwards, the closer my camera will be to the bottom of my local player. If you imagine playing a third person game you should understand what I mean.

Here's the calculation I'm doing:

Vector3 vForwardVector = vTargetPosition - vCameraPosition; Vector2 vCalculatedAngle = Vector2(atan2(vForwardVector.x, vForwardVector.z), atan2(vForwardVector.y, sqrt(vForwardVector.x * vForwardVector.x + vForwardVector.z * vForwardVector.z)));

I'm not sure what other detail I can provide.. hoping someone can point out an obvious mistake? Happy to provide any extra information!

Thank you everyone.

• If you stop using angles and just used vForwardVector to represent the aim direction your code will be simpler and have less bugs. Vector math is better than managing angles. – James Lambert Mar 15 '17 at 17:19

## 1 Answer

Sounds like you just always need to use the players eye position instead of the camera position for the calculation.

• In that case, the calculated angle wouldn't be correct unless in first person. The viewangle is based on the camera position, so if you used the eye position when in third person, the calculation would be useless. – user7716080 Mar 15 '17 at 17:28