I have two vectors in the game. One vector is a player, one vector is an object. I also have a vector that determines the direction of the player, if he is facing. The direction vector does not have a z-part. This is a point that has a value of 1, located somewhere around the origin.
I want to calculate the angle between the direction the soldier is in and the object, so I can correctly pan some sound (stereo only).
The diagram below describes my problem. I want to calculate the angle between two dashed lines. One dashed line connects the player and the object, and the other a line representing the direction the player is facing from the point the player is at.

I'm currently doing this (suppose the player, object and direction are all vectors with three points, x, y and z):
Vector3d v1 = direction; Vector3d v2 = object - player; v1.normalise(); v2.normalise(); float angle = acos(dotProduct(v1, v2));
But that seems to give me the wrong results. Any tips?
Code Verification:
Vector3d soldier = Vector3d(1.f, 1.f, 0.f); Vector3d object = Vector3d(1.f, -1.f, 0.f); Vector3d dir = Vector3d(1.f, 0.f, 0.f); Vector3d v1 = dir; Vector3d v2 = object - soldier; long steps = 360; for (long step = 0; step < steps; step++) { float rad = (float)step * (M_PI / 180.f); v1.x = cosf(rad); v1.y = sinf(rad); v1.normalise(); float dx = dotProduct(v2, v1); float dy = dotProduct(v2, soldier); float vangle = atan2(dx, dy); }
source share