2018-11-30 02:41:06 +00:00
using Microsoft.Xna.Framework ;
using Microsoft.Xna.Framework.Graphics ;
using System ;
2018-12-04 13:45:09 +00:00
namespace RecrownedAthenaeum.Camera
2018-11-30 02:41:06 +00:00
{
2019-01-14 06:34:35 +00:00
/// <summary>
/// A virtual 2D camera.
/// </summary>
2018-11-30 02:41:06 +00:00
public class Camera2D
{
2019-01-14 06:34:35 +00:00
/// <summary>
/// Current zoom level.
/// </summary>
2018-11-30 02:41:06 +00:00
public float Zoom ;
2019-01-14 06:34:35 +00:00
/// <summary>
/// Current position in the world.
/// </summary>
2018-11-30 02:41:06 +00:00
public Vector2 Position ;
2019-01-14 06:34:35 +00:00
/// <summary>
/// The matrix representing the zoom and position.
/// </summary>
2019-01-12 04:09:42 +00:00
public Matrix Matrix { get ; private set ; }
2018-11-30 02:41:06 +00:00
2019-01-30 13:46:58 +00:00
private GraphicsDevice graphicsDevice ;
2019-01-14 06:34:35 +00:00
/// <summary>
/// Constructs 2D camera.
/// </summary>
2019-01-22 04:18:22 +00:00
/// <param name="graphicsDevice">The graphics device to use. Will use graphics device from <see cref="Configuration"/>'s graphics device manager if this is null which it is by default.</param>
2019-01-22 01:56:51 +00:00
public Camera2D ( GraphicsDevice graphicsDevice = null )
2018-11-30 02:41:06 +00:00
{
2019-01-30 13:46:58 +00:00
this . graphicsDevice = graphicsDevice ? ? ( Configuration . GraphicsDeviceManager . GraphicsDevice ) ;
2019-01-22 01:56:51 +00:00
2018-11-30 02:41:06 +00:00
Zoom = 1f ;
Position . X = this . graphicsDevice . Viewport . Width * 0.5f ;
Position . Y = this . graphicsDevice . Viewport . Height * 0.5f ;
}
2019-01-14 06:34:35 +00:00
/// <summary>
/// Applies any changes made to the properties of this camera and updates to new dimensions of viewport specified by the graphics device.
/// </summary>
2018-11-30 02:41:06 +00:00
public void Update ( )
{
Rectangle bounds = graphicsDevice . Viewport . Bounds ;
2019-01-12 04:09:42 +00:00
Matrix =
2018-11-30 02:41:06 +00:00
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 ) ) ;
}
2019-01-14 06:34:35 +00:00
/// <summary>
/// Lerps to the given position.
/// </summary>
/// <param name="alpha">The multiplier for difference in distance.</param>
/// <param name="targetPosition">The target position to lerp to.</param>
/// <param name="delta">Time between this frame and the previous frame.</param>
2018-11-30 02:41:06 +00:00
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 ;
}
}
}