MoonWorks/src/Input/ButtonState.cs

98 lines
2.2 KiB
C#
Raw Normal View History

2022-02-23 05:14:32 +00:00
namespace MoonWorks.Input
2021-01-19 07:29:07 +00:00
{
/// <summary>
/// Container for the current state of a binary input.
/// </summary>
2022-03-07 18:54:52 +00:00
public struct ButtonState
2022-02-23 05:14:32 +00:00
{
2022-03-18 18:46:44 +00:00
public ButtonStatus ButtonStatus { get; }
2021-01-22 22:41:34 +00:00
/// <summary>
/// True if the button was pressed this frame.
/// </summary>
2022-02-23 05:14:32 +00:00
public bool IsPressed => ButtonStatus == ButtonStatus.Pressed;
/// <summary>
/// True if the button was pressed this frame and the previous frame.
/// </summary>
2022-02-23 05:14:32 +00:00
public bool IsHeld => ButtonStatus == ButtonStatus.Held;
/// <summary>
/// True if the button was either pressed or continued to be held this frame.
/// </summary>
2022-02-23 05:14:32 +00:00
public bool IsDown => ButtonStatus == ButtonStatus.Pressed || ButtonStatus == ButtonStatus.Held;
/// <summary>
/// True if the button was let go this frame.
/// </summary>
2022-02-23 05:14:32 +00:00
public bool IsReleased => ButtonStatus == ButtonStatus.Released;
/// <summary>
/// True if the button was not pressed this frame or the previous frame.
/// </summary>
public bool IsIdle => ButtonStatus == ButtonStatus.Idle;
/// <summary>
/// True if the button was either idle or released this frame.
/// </summary>
public bool IsUp => ButtonStatus == ButtonStatus.Idle || ButtonStatus == ButtonStatus.Released;
2021-01-22 22:41:34 +00:00
public ButtonState(ButtonStatus buttonStatus)
2022-03-07 18:54:52 +00:00
{
ButtonStatus = buttonStatus;
}
internal ButtonState Update(bool isPressed)
2022-02-23 05:14:32 +00:00
{
if (isPressed)
{
if (IsUp)
{
return new ButtonState(ButtonStatus.Pressed);
}
else
2022-02-23 05:14:32 +00:00
{
2022-03-07 18:54:52 +00:00
return new ButtonState(ButtonStatus.Held);
2022-02-23 05:14:32 +00:00
}
}
else
{
if (IsDown)
2022-02-23 05:14:32 +00:00
{
return new ButtonState(ButtonStatus.Released);
2022-03-07 18:54:52 +00:00
}
else
2022-03-07 18:54:52 +00:00
{
return new ButtonState(ButtonStatus.Idle);
2022-02-23 05:14:32 +00:00
}
}
}
2022-07-13 00:57:27 +00:00
/// <summary>
/// Combines two button states. Useful for alt control sets or input buffering.
/// </summary>
2022-07-13 00:57:27 +00:00
public static ButtonState operator |(ButtonState a, ButtonState b)
{
if (a.ButtonStatus == ButtonStatus.Idle || a.ButtonStatus == ButtonStatus.Released)
2022-07-13 00:57:27 +00:00
{
return b;
}
else if (a.ButtonStatus == ButtonStatus.Pressed)
{
if (b.ButtonStatus == ButtonStatus.Held)
{
return new ButtonState(ButtonStatus.Held);
}
else
{
return a;
}
}
else // held
{
return a;
}
}
2022-02-23 05:14:32 +00:00
}
2021-01-19 07:29:07 +00:00
}