2D Camera Class for XNA
Camera2D.cs
This is a locked, single-post thread from Creation Asylum. Archived here to prevent its loss.
No support is given. If you are the owner of the thread, please contact administration.
Info
This is a nice camera taken from David Amador , so all credits go to him.
This camera is a great way to extend your game world beyond the restrictions of screen resolution and allowing you to create large expansive worlds with ease.
I would recommend using GoldenShado's beginner xna tutorial if you have no codebase to apply this too.
Demo
Demo Coming Soon
Script
"Camera2D.cs"
Code:
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Camera2D
{
class Camera2D
{
protected float _zoom; // Camera Zoom
protected float _rotation; // Camera Rotation
public Matrix _transform; // Matrix Transform
public Vector2 _pos; // Camera Position
public Camera2D()
{
_zoom = 1.0f;
_rotation = 0.0f;
_pos = Vector2.Zero;
}
public float Zoom
{
get { return _zoom; }
set
{
_zoom = value;
if (_zoom < 0.1f) { _zoom = 0.1f; }
} // Negative zoom will flip image
}
// Auxiliary function to move the camera
public void Move(Vector2 amount)
{
_pos += amount;
}
public Vector2 Pos
{
get { return _pos; }
set { _pos = value; }
}
public Matrix get_transformation(GraphicsDeviceManager graphicsDevice)
{
_transform =
Matrix.CreateTranslation(new Vector3(-_pos.X, -_pos.Y, 0)) *
Matrix.CreateRotationZ(_rotation) *
Matrix.CreateScale(new Vector3(Zoom, Zoom, 0)) *
Matrix.CreateTranslation(Vector3.Zero);
return _transform;
}
public void Update(Vector2 target)
{
_pos = target;
}
}
}
Usage
To use this create an instance at the top of your Main Game class, for this topic I will assume it's Game1.cs
Then in the Initialize method you initialize it.
Code:
camera = new Camera2D();
Then in the Update method you call the cameras update and pass in parameters, where parameter one (target) is the focus of camera, where the top left will begin.
Code:
camera.Update(new Vector2(200,200))
Finally in the Draw method of Game1 change the line
If XNA 3.1 change it to this.
Code:
spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.SaveState, camera.get_transformation(graphics))
If XNA 4 change it to this.
Code:
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, null, null, null, camera.get_transformation(graphics))
To extend this
Try swapping new Vector2(200,200) with a constantly changing value, perhaps a player position.
Play around with the _zoom and _rotate values, you can get some fun effects using a similar method as with _pos