61 lines
2.1 KiB
C#
61 lines
2.1 KiB
C#
using System;
|
|
|
|
using Microsoft.Xna.Framework.Input;
|
|
|
|
using Syntriax.Engine.Core;
|
|
using Syntriax.Engine.Systems.Input;
|
|
|
|
namespace Pong.Behaviours;
|
|
|
|
public class PaddleBehaviour(Keys Up, Keys Down, float High, float Low, float Speed) : Behaviour2D
|
|
{
|
|
private Keys Up { get; } = Up;
|
|
private Keys Down { get; } = Down;
|
|
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 IButtonInputs<Keys> inputs = null!;
|
|
|
|
protected override void OnUpdate()
|
|
{
|
|
if (isUpPressed && isDownPressed)
|
|
return;
|
|
|
|
if (isUpPressed)
|
|
Transform.Position = Transform.Position + Vector2D.Up * GameManager.Time.DeltaTime * Speed;
|
|
else if (isDownPressed)
|
|
Transform.Position = Transform.Position + -Vector2D.Up * GameManager.Time.DeltaTime * Speed;
|
|
|
|
Transform.Position = new Vector2D(Transform.Position.X, MathF.Max(MathF.Min(Transform.Position.Y, High), Low));
|
|
}
|
|
|
|
protected override void OnFirstActiveFrame()
|
|
{
|
|
inputs = GameManager.FindBehaviour<IButtonInputs<Keys>>() ?? throw new("Unable to find inputs");
|
|
|
|
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(IButtonInputs<Keys> inputs, Keys keys) => isUpPressed = true;
|
|
private void OnUpReleased(IButtonInputs<Keys> inputs, Keys keys) => isUpPressed = false;
|
|
private void OnDownPressed(IButtonInputs<Keys> inputs, Keys keys) => isDownPressed = true;
|
|
private void OnDownReleased(IButtonInputs<Keys> inputs, Keys keys) => isDownPressed = false;
|
|
}
|