rj-action-library/Runtime/Sensors/KeySensor.cs

110 lines
2.2 KiB
C#

using Godot;
namespace Rokojori
{
[GlobalClass,Icon("res://addons/rokojori_action_library/Icons/RJSensor.svg")]
public partial class KeySensor : RJSensor
{
[Export]
public Key key;
[ExportGroup( "Modifiers")]
[Export]
public Trillean ctrlHold = Trillean.Any;
[Export]
public Trillean altHold = Trillean.Any;
[Export]
public Trillean shiftHold = Trillean.Any;
public bool modifiersEnabled => TrilleanLogic.AllAny( ctrlHold, altHold, shiftHold );
public enum ModifiersMode
{
Hold_Modifiers_Only_On_Down,
Hold_Modifiers_All_The_Time
}
[Export]
public ModifiersMode modifiersMode;
bool _isActive;
bool _wasActive;
float _value = 0;
float axisActivationTreshold = 0.5f;
float _lastInput = 0;
public override void _Process( double delta )
{
UpdateValue( _lastInput );
}
public override void _Input( InputEvent ev )
{
var keyEvent = ev as InputEventKey;
if ( keyEvent == null )
{
return;
}
if ( keyEvent.Keycode != key)
{
return;
}
var checkModifiers = modifiersEnabled &&
(
ModifiersMode.Hold_Modifiers_All_The_Time == modifiersMode ||
_lastInput == 0 && ModifiersMode.Hold_Modifiers_Only_On_Down == modifiersMode
);
if ( checkModifiers )
{
if ( ! TrilleanLogic.Matches( ctrlHold, keyEvent.CtrlPressed ) )
{
_lastInput = 0;
return;
}
if ( ! TrilleanLogic.Matches( altHold, keyEvent.AltPressed ) )
{
_lastInput = 0;
return;
}
if ( ! TrilleanLogic.Matches( shiftHold, keyEvent.ShiftPressed ) )
{
_lastInput = 0;
return;
}
}
_lastInput = keyEvent.IsPressed() ? 1 : 0;
}
public override bool IsActive()
{
return _isActive;
}
public override bool WasActive()
{
return _wasActive;
}
public override void UpdateValue( float value )
{
_value = value;
_wasActive = _isActive;
_isActive = _value > axisActivationTreshold;
}
}
}