Engine-Pong/Game/Behaviours/CameraController.cs

56 lines
2.4 KiB
C#

using Microsoft.Xna.Framework.Input;
using Syntriax.Engine.Core;
using Syntriax.Engine.Input;
namespace Pong.Behaviours;
public class CameraController : BehaviourOverride
{
private MonoGameCameraBehaviour cameraBehaviour = null!;
private IButtonInputs<Keys> buttonInputs = null!;
protected override void OnFirstActiveFrame()
{
if (BehaviourController.TryGetBehaviour(out MonoGameCameraBehaviour? foundCameraBehaviour))
cameraBehaviour = foundCameraBehaviour;
cameraBehaviour ??= BehaviourController.AddBehaviour<MonoGameCameraBehaviour>();
if (BehaviourController.TryGetBehaviour(out IButtonInputs<Keys>? foundButtonInputs))
buttonInputs = foundButtonInputs;
buttonInputs ??= BehaviourController.AddBehaviour<KeyboardInputsBehaviour>();
buttonInputs.RegisterOnPress(Keys.F, SwitchToFullScreen);
}
protected override void OnUpdate()
{
if (buttonInputs.IsPressed(Keys.U))
cameraBehaviour.Zoom += Time.Elapsed.Nanoseconds * 0.00025f;
if (buttonInputs.IsPressed(Keys.J))
cameraBehaviour.Zoom -= Time.Elapsed.Nanoseconds * 0.00025f;
if (buttonInputs.IsPressed(Keys.Q))
cameraBehaviour.BehaviourController.GameObject.Transform.Rotation += Time.Elapsed.Nanoseconds * 0.000025f;
if (buttonInputs.IsPressed(Keys.E))
cameraBehaviour.BehaviourController.GameObject.Transform.Rotation -= Time.Elapsed.Nanoseconds * 0.000025f;
}
private void SwitchToFullScreen(IButtonInputs<Keys> inputs, Keys keys)
{
if (Game1.graphics.IsFullScreen)
return;
Game1.graphics.PreferMultiSampling = false;
Game1.graphics.PreferredBackBufferWidth = Game1.graphics.GraphicsDevice.Adapter.CurrentDisplayMode.Width;
Game1.graphics.PreferredBackBufferHeight = Game1.graphics.GraphicsDevice.Adapter.CurrentDisplayMode.Height;
Game1.graphics.IsFullScreen = true;
Game1.graphics.ApplyChanges();
float previousScreenSize = Math.Sqrt(Math.Pow(cameraBehaviour.Viewport.Width, 2f) + Math.Pow(cameraBehaviour.Viewport.Height, 2f));
float currentScreenSize = Math.Sqrt(Math.Pow(Game1.graphics.GraphicsDevice.Viewport.Width, 2f) + Math.Pow(Game1.graphics.GraphicsDevice.Viewport.Height, 2f));
cameraBehaviour.Zoom /= previousScreenSize / currentScreenSize;
cameraBehaviour.Viewport = Game1.graphics.GraphicsDevice.Viewport;
}
}