title: Calculate Angle from Two Points and a Direction Vector
body: <p>I have two vectors in a game. One vector is the player, one vector is an object. I also have a vector that specifies the direction the player if facing. The direction vector has no z part. It is a point that has a magnitude of 1 placed somewhere around the origin.</p>
  
  <p>I want to calculate the angle between the direction the soldier is currently facing and the object, so I can correctly pan some audio (stereo only).</p>
  
  <p>The diagram below describes my problem. I want to calculate the angle between the two dashed lines. One dashed line connects the player and the object, and the other is a line representing the direction the player is facing from the point the player is at.</p>
  
  <p><img src="https://i.stack.imgur.com/FuXTH.png" alt="Angle Problem"></p>
  
  <p>At the moment, I am doing this (assume player, object and direction are all vectors with 3 points, x, y and z):</p>
  
  <pre><code>Vector3d v1 = direction;
  Vector3d v2 = object - player;
  v1.normalise();
  v2.normalise();
  float angle = acos(dotProduct(v1, v2));
  </code></pre>
  
  <p>But it seems to give me incorrect results. Any advice?</p>
  
  <p>Test of code:</p>
  
  <pre><code>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 &lt; 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);
  }
  </code></pre>