Engine-Pong/Game/Behaviours/MovementBoxBehaviour.cs

63 lines
2.3 KiB
C#
Raw Normal View History

using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Syntriax.Engine.Core;
using Syntriax.Engine.Input;
namespace Pong.Behaviours;
2023-11-27 17:06:18 +03:00
public class MovementBoxBehaviour(Keys Up, Keys Down, float High, float Low, float Speed) : BehaviourOverride
{
private Keys Up { get; } = Up;
private Keys Down { get; } = Down;
2023-11-27 17:06:18 +03:00
public float High { get; } = High;
public float Low { get; } = Low;
public float Speed { get; set; } = Speed;
private bool isUpPressed = false;
private bool isDownPressed = false;
private IKeyboardInputs inputs = null!;
protected override void OnUpdate(GameTime time)
{
if (isUpPressed && isDownPressed)
return;
if (isUpPressed)
GameObject.Transform.Position = GameObject.Transform.Position + Vector2.UnitY * (float)time.ElapsedGameTime.TotalSeconds * Speed;
else if (isDownPressed)
GameObject.Transform.Position = GameObject.Transform.Position + -Vector2.UnitY * (float)time.ElapsedGameTime.TotalSeconds * Speed;
2023-11-27 17:06:18 +03:00
GameObject.Transform.Position = new Vector2(GameObject.Transform.Position.X, MathF.Max(MathF.Min(GameObject.Transform.Position.Y, High), Low));
}
protected override void OnFirstActiveFrame(GameTime time)
{
2023-11-27 17:41:21 +03:00
if (!BehaviourController.TryGetBehaviour<IKeyboardInputs>(out var behaviourResult))
throw new Exception($"{nameof(IKeyboardInputs)} is missing on ${GameObject.Name}.");
2023-11-27 17:41:21 +03:00
inputs = behaviourResult;
inputs.RegisterOnPress(Up, OnUpPressed);
inputs.RegisterOnRelease(Up, OnUpReleased);
inputs.RegisterOnPress(Down, OnDownPressed);
inputs.RegisterOnRelease(Down, OnDownReleased);
}
protected override void OnFinalize()
{
inputs.UnregisterOnPress(Up, OnUpPressed);
inputs.UnregisterOnRelease(Up, OnUpReleased);
inputs.UnregisterOnPress(Down, OnDownPressed);
inputs.UnregisterOnRelease(Down, OnDownReleased);
}
private void OnUpPressed(IKeyboardInputs inputs, Keys keys) => isUpPressed = true;
private void OnUpReleased(IKeyboardInputs inputs, Keys keys) => isUpPressed = false;
private void OnDownPressed(IKeyboardInputs inputs, Keys keys) => isDownPressed = true;
private void OnDownReleased(IKeyboardInputs inputs, Keys keys) => isDownPressed = false;
}