title: Unproject MouseCoords ( OpenGL / OpenTK ).
body: <p>Hey I am trying to convert 2d mouse coords to a 3d direction vector to world space. The problem is that the direction vector of the ray is only fully working if the camera is not turning in Y-axis. For example: Camera looking down. Y is -0.999 thats perfect, but now I turn the camera 90° in Y-axis and the result is that X is now -0.999 and Y very small ( but still looking down ). The only direction thats working is Z.</p>
  
  <p>This is the code for getting the mouse ray.</p>
  
  <pre><code>        public Vector3 get3DMouseCoords(int mousex, int mousey)
      {
          Vector2 normalizedCoords = getNormalizedMouseCoords(mousex, mousey);
          Vector4 clipCoords = new Vector4(normalizedCoords.X, normalizedCoords.Y, -1f, 1f);
          Vector4 eyeRay = getEyeRay(clipCoords);
          return getWorldRay(eyeRay);
      } 
  
      private Vector3 getWorldRay(Vector4 eyeRay)
      {
          Matrix4 invertertedView = Matrix4.Invert(Camera.Transformation);
          Vector3 worldRay = Vector4.Transform(invertertedView, eyeRay).Xyz;
          return worldRay.Normalized();
      }
  
      private Vector4 getEyeRay(Vector4 clipCoords)
      {
          Matrix4 invertertedProj = Matrix4.Invert(Camera.PerspectiveProjection);
          Vector4 eyeRay = Vector4.Transform(invertertedProj, clipCoords);
          return new Vector4(eyeRay.X, eyeRay.Y, -1f, 0f);
      }
  
      private Vector2 getNormalizedMouseCoords(int mousex, int mousey)
      {
          float x = 2.0f * mousex / (float)screenWidth - 1;
          float y = -(2.0f * mousey / (float)screenHeight - 1);
          return new Vector2(x, y);
      }
  </code></pre>
  
  <p>This is the view matrix code:</p>
  
  <pre><code>                    Vector3 lookat = new Vector3();
  
                  lookat.X = (float)(Math.Sin((float)orientation.X) * Math.Cos((float)orientation.Y));
                  lookat.Y = (float)Math.Sin((float)orientation.Y);
                  lookat.Z = (float)(Math.Cos((float)orientation.X) * Math.Cos((float)orientation.Y));
  
                  view = Matrix4.LookAt(Position, Position + lookat, Vector3.UnitY);
  </code></pre>
  
  <p>Thanks in Advance.</p>