Archive | Code RSS for this section

3 Thing Game

Heres the results of the second time entering the 3 Thing Game Competition. I’m pretty pleased with the way the game turned out, especially that we were able to get 2 player split screen working 😀

Advertisements

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.