title: Rotating a cube with the mouse using OpenGL
body: <p>I am using OpenGL and GLUT to display a cube. I now want to be able to rotate the camera around the cube by dragging the mouse across the window. When the mouse moves horizontally, the cube should rotate around its vertical axis, and when the mouse moves vertically, the cube should rotate around its horizontal axis, both at a fixed distance <code>d</code>.</p>
  
  <p>To achieve this, I have tried representing the camera in spherical coordinates, <code>theta</code> and <code>phi</code>. When the mouse moves horizontally across the screen, I increase (right) or decrease (left) <code>theta</code>, and when the mouse moves vertically, I increase (up) or decrease (down) <code>phi</code>. Then, I use the following equations to determine the Cartesian position of the camera and the associated view matrix:</p>
  
  <pre><code>float eye_x = d * sin(phi) * cos(theta);
  float eye_y = d  * sin(phi) * sin(theta);
  float eye_z = d  * cos(phi);
  glm::vec3 centre(0.0f, 0.0f, 0.0f);
  glm::vec3 up(0, 1, 0);
  view_matrix = glm::lookAt(eye, centre, up);
  </code></pre>
  
  <p>When I run this code, the cube does rotate as I move the mouse around the window, but not in the way I would expect. Also, the cube seems to "flip" its orientation suddenly at certain points.</p>
  
  <p>Can somebody point me in the right direction as to how I should properly implement this?</p>