title: XNA Camera Rotation Around Z Axis
body: <p>I'm creating a camera for a 3D game. The camera is made up of the following variables:</p>
  
  <pre><code>static Vector3 cameraLookAt = new Vector3(0, 0, 0);
  static Vector3 cameraPosition;
  static float cameraZoom = 25; // Field of view 
  const int cameraZoomNear = 3; // The furthest the camera can zoom in 
  const int cameraZoomFar = 45; // The furthest the camera can zoom out 
  static float cameraPitch; // Amount to change the pitch 
  static float cameraRotation; // Amount to change the rotation
  </code></pre>
  
  <p>By default the 'cameraLookAt' is at (0, 0, 0) and the 'cameraPosition' is at (0, 0, 10) this means the camera is directly above the 'cameraLookAt' position giving a birds eye view of the object below (a red green &amp; blue xyz plane test object)</p>
  
  <p>'cameraLookAt' can be moved along the x and y axis and the 'cameraPosition' is then calculated relative to the 'cameraLookAt' position and the current values of 'cameraPitch' and 'cameraRotation'</p>
  
  <p>Currently you can move around the x/y axis fine and change the pitch of the camera to go from a birdeye view to a ground view. The bit I'm having trouble with is getting the camera rotation to work.</p>
  
  <p>When the rotation value is changed it only has any effect if the pitch has changed - from the default when the program starts (which is looking directly down at the 'cameraLookAt')</p>
  
  <p>When the value does change you can rotate around the Z axis but the view also rolls so by the time you have rotated 180 degrees the camera has rolled 180 degrees as well and your view is upside down.</p>
  
  <p>Below is the code which works out where the 'cameraPosition' is and I'm sure the fix lines within those lines.</p>
  
  <pre><code>        cameraPosition = cameraLookAt + new Vector3(0, 0, 10);
  
          Vector3 temp = Vector3.Normalize(cameraPosition - cameraLookAt); //creates a unit length vector that points in the direction from 'lookAt' to 'position'
          cameraPosition = Vector3.Transform(cameraPosition - cameraLookAt, Matrix.CreateRotationX(cameraPitch)) + cameraLookAt;
          cameraPosition = Vector3.Transform(cameraPosition - cameraLookAt, Matrix.CreateRotationZ(cameraRotation)) + cameraLookAt;
  
          view = Matrix.CreateLookAt(cameraPosition, cameraLookAt, new Vector3(0.0f, 1.0f, 0.0f));
          projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(cameraZoom), graphics.GraphicsDevice.Viewport.AspectRatio, nearClip, farClip);
  </code></pre>
  
  <p>Also here is a q&amp;a that I found to help me code it in the first place <a href="https://stackoverflow.com/questions/5906907/xna-rotate-camera-around-its-createlookat-target">XNA Rotate Camera Around It&#39;s CreateLookAt &quot;Target&quot;</a></p>