title: XNA ViewPort projection and SpriteBatch
body: <p>I'm working on an XNA game and I am using ViewPort.Project and ViewPort.Unproject to translate to and from world coordinates. Currently I use these for each object I draw with SpriteBatch. What I would like to do is calculate a Matrix that I can send to SpriteBatch.Begin to do the screen-space transformation for me. </p>
  
  <p>Here are the functions I currently use to translate to and from screenspace:</p>
  
  <pre><code>        Vector2 ToWorldCoordinates(Vector2 pixels)
      {
          Vector3 worldPosition = graphics.GraphicsDevice.Viewport.Unproject(new Vector3(pixels, 0),
                  Projection, View, Matrix.Identity);
          return new Vector2(worldPosition.X, worldPosition.Y);
      }
  
      Vector2 ToScreenCoordinates(Vector2 worldCoords)
      {
          var screenPositon = graphics.GraphicsDevice.Viewport.Project(new Vector3(worldCoords, 0),
                  Projection, View, Matrix.Identity);
          return new Vector2(screenPositon.X, screenPositon.Y);
      }
  </code></pre>
  
  <p>View is set to Matrix.Identity, and Projection is set like so:</p>
  
  <pre><code>Projection = Matrix.CreateOrthographic(40 * graphics.GraphicsDevice.Viewport.AspectRatio, 40, 0, 1);
  </code></pre>
  
  <p>And here is how I currently draw things:</p>
  
  <pre><code>            spriteBatch.Begin();
          foreach (var thing in thingsToDraw)
          {
              spriteBatch.Draw(thing.Texture, ToScreenCoordinates(thing.PositionInWorldCoordinates), thing.Color);
              spriteBatch.End();
          }
          spriteBatch.End();
  </code></pre>
  
  <p>This is what I would like to do instead (using XNA 4.0 version of SpriteBatch.Begin())</p>
  
  <pre><code>            // how do I calculate this matrix?
          Matrix myTransformationMatrix = GetMyTransformationMatrix();
  
          spriteBatch.Begin(SpriteSortMode.Immediate, null, null, null, null, null,
              myTransformationMatrix);
  
          foreach (var thing in thingsToDraw)
          {
              // note: no longer converting each object's position to screen coordinates
              spriteBatch.Draw(thing.Texture, thing.PositionInWorldCoordinates, thing.Color);
              spriteBatch.End();
          }
          spriteBatch.End();
  </code></pre>