using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; namespace RecrownedAthenaeum.Camera { /// /// A virtual 2D camera. /// public class Camera2D { /// /// Current zoom level. /// public float Zoom; /// /// Current position in the world. /// public Vector2 Position; /// /// The matrix representing the zoom and position. /// public Matrix Matrix { get; private set; } private GraphicsDevice graphicsDevice = Configuration.graphicsDeviceManager.GraphicsDevice; /// /// Constructs 2D camera. /// /// The graphics device to use. Will use graphics device from 's graphics device manager if this is null which it is by default. public Camera2D(GraphicsDevice graphicsDevice = null) { if (graphicsDevice != null) this.graphicsDevice = graphicsDevice; if (this.graphicsDevice == null) throw new ArgumentNullException("Graphics device can't be null in setup and argument. One must not be null for use."); Zoom = 1f; Position.X = this.graphicsDevice.Viewport.Width * 0.5f; Position.Y = this.graphicsDevice.Viewport.Height * 0.5f; } /// /// Applies any changes made to the properties of this camera and updates to new dimensions of viewport specified by the graphics device. /// public void Update() { Rectangle bounds = graphicsDevice.Viewport.Bounds; Matrix = Matrix.CreateTranslation(new Vector3(-Position.X, -Position.Y, 0)) * Matrix.CreateScale(Zoom) * Matrix.CreateTranslation(new Vector3(bounds.Width * 0.5f, bounds.Height * 0.5f, 0f)); } /// /// Lerps to the given position. /// /// The multiplier for difference in distance. /// The target position to lerp to. /// Time between this frame and the previous frame. public void LinearInterpolationToPosition(float alpha, Vector2 targetPosition, float delta) { if (alpha <= 0 && alpha > 1f) throw new ArgumentException("Alpha can't be greater than 1f, less than or equal to 0."); Vector2 distance = targetPosition - Position; distance *= (float)(1.0f - Math.Pow(1 - alpha, delta / 0.02f)); Position += distance; } } }