Ridiculously simple XNA camera scrolling

Before, when i’ve been working on projects where the scene is bigger than the window I’ve been setting up an offset value which can be edited whenever needed, then shifting each sprite’s position by it when the sprite is drawn. Having flicked through a few tutorials its apparent that this can be achieved much easier by creating a camera class which you can shift about, and using that in the SpritBatch’s Begin call so effect everything within the SpriteBatch.

Here is a quick and dirty camera class in C#. In the main update loop you need to call the Camera’s update method, and pass it the keyboard’s current state (Keyboard.GetState()):

class Camera
{
static Vector2 offset = Vector2.Zero;

public static Matrix GetMatrix()
{
Matrix Transformation = Matrix.CreateTranslation(new Vector3(-offset.X, -offset.Y, 0));
return Transformation;
}

public static void Update(KeyboardState keyboard)
{
if (keyboard.IsKeyDown(Keys.Left))
{
offset.X -= 5;
}
if (keyboard.IsKeyDown(Keys.Right))
{
offset.X += 5;
}
if (keyboard.IsKeyDown(Keys.Up))
{
offset.Y -= 5;
}
if (keyboard.IsKeyDown(Keys.Down))
{
offset.Y += 5;
}
}
}

And this is your new SpriteBatch.Draw() call:

spriteBatch.Begin(SpriteSortMode.Immediate,
BlendState.AlphaBlend,
null,
null,
null,
null,
Camera.GetMatrix());

Theres a more in depth tutorial here if you need it, which also covers rotation and zooming.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: