Engine-Pong/Game/Behaviours/MonoGameCameraBehaviour.cs

85 lines
2.1 KiB
C#
Raw Normal View History

2024-01-22 23:47:47 +03:00
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Syntriax.Engine.Core;
namespace Pong.Behaviours;
2024-01-31 12:51:23 +03:00
public class MonoGameCameraBehaviour(GraphicsDeviceManager Graphics) : BehaviourOverride
2024-01-22 23:47:47 +03:00
{
2024-01-30 12:15:26 +03:00
public System.Action<MonoGameCameraBehaviour>? OnMatrixTransformChanged { get; set; } = null;
public System.Action<MonoGameCameraBehaviour>? OnViewportChanged { get; set; } = null;
public System.Action<MonoGameCameraBehaviour>? OnZoomChanged { get; set; } = null;
2024-01-22 23:47:47 +03:00
private Matrix _matrixTransform = Matrix.Identity;
private Viewport _viewport = default;
private float _zoom = 1f;
2024-01-31 12:51:23 +03:00
public GraphicsDeviceManager Graphics { get; } = Graphics;
2024-01-22 23:47:47 +03:00
public Matrix MatrixTransform
{
get => _matrixTransform;
set
{
if (_matrixTransform == value)
return;
_matrixTransform = value;
OnMatrixTransformChanged?.Invoke(this);
}
}
public Vector2D Position
{
get => Transform.Position;
set => Transform.Position = value;
}
public Viewport Viewport
{
get => _viewport;
set
{
if (_viewport.Equals(value))
return;
_viewport = value;
OnViewportChanged?.Invoke(this);
}
}
public float Zoom
{
get => _zoom;
set
{
2024-01-30 12:15:26 +03:00
float newValue = Math.Max(0.1f, value);
2024-01-22 23:47:47 +03:00
if (_zoom == newValue)
return;
_zoom = newValue;
OnZoomChanged?.Invoke(this);
}
}
public float Rotation
{
get => Transform.Rotation;
set => Transform.Rotation = value;
}
2024-01-30 12:59:41 +03:00
protected override void OnFirstActiveFrame()
=> Viewport = Graphics.GraphicsDevice.Viewport;
2024-01-30 12:59:41 +03:00
2024-01-30 12:14:49 +03:00
protected override void OnPreDraw()
2024-01-22 23:47:47 +03:00
{
MatrixTransform =
Matrix.CreateTranslation(new Vector3(-Position.X, Position.Y, 0f)) *
Matrix.CreateRotationZ(Rotation) *
Matrix.CreateScale(Zoom) *
Matrix.CreateTranslation(new Vector3(_viewport.Width * .5f, _viewport.Height * .5f, 0f));
}
}