Engine-Pong/Game/Behaviours/MovementBoxBehaviour.cs

57 lines
2.0 KiB
C#

using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Syntriax.Engine.Core;
using Syntriax.Engine.Input;
namespace Pong.Behaviours;
public class MovementBoxBehaviour(Keys Up, Keys Down, float Speed) : BehaviourOverride
{
private Keys Up { get; } = Up;
private Keys Down { get; } = Down;
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;
}
protected override void OnInitialize()
{
if (!BehaviourController.TryGetBehaviour(out inputs))
throw new Exception($"{nameof(IKeyboardInputs)} is missing on ${GameObject.Name}.");
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;
}