carotrauma/scripts/libs/input/InputContext.cs
Nick Guy c98d7739aa
All checks were successful
/ build (push) Successful in 1m32s
Add custom input mapping on top of Godot's InputMap
2024-06-02 17:10:15 +01:00

65 lines
1.7 KiB
C#

using System;
using System.Collections.Generic;
using System.Text;
using Godot;
namespace Carotrauma.scripts.libs.input;
public partial class InputContext : Node {
public override void _Ready() {
LoadContext();
}
public override void _ExitTree() {
UnloadContext();
base._ExitTree();
}
private List<InputAction> _actions;
private double cooldown = 1;
public override void _Process(double delta) {
cooldown -= delta;
if (cooldown > 0) return;
cooldown = 5;
GD.Print(ToString());
}
public void LoadContext() {
var provider = GetParentOrNull<Node3D>();
if (provider is not IInputProvider inputProvider) return;
_actions = inputProvider.Actions;
_actions.ForEach(LoadAction);
}
public void UnloadContext() {
_actions?.ForEach(UnloadAction);
}
private void LoadAction(InputAction action) {
GD.Print("Add action: " + action.Name);
InputMap.AddAction(action.Name);
GD.Print("Add event to action: " + action.Name);
InputMap.ActionAddEvent(action.Name, action.Event);
}
private void UnloadAction(InputAction action) {
InputMap.ActionEraseEvent(action.Name, action.Event);
InputMap.EraseAction(action.Name);
}
public override string ToString() {
if (_actions == null) return "No Actions";
StringBuilder sb = new();
sb.AppendLine("Input Context:");
foreach (InputAction action in _actions) {
sb.Append(" - ").AppendLine(action.Name);
foreach (var inputEvent in InputMap.ActionGetEvents(action.Name))
sb.Append(" - ").AppendLine(inputEvent.AsText());
}
return sb.ToString();
}
}