@@ -97,17 +97,56 @@ private void LoadControlScheme()
9797 }
9898
9999 var selectedScheme = ControlSchemes . Schemes [ scheme ] ;
100+
100101 foreach ( var arrow in Arrows )
101102 {
102103 if ( selectedScheme . ContainsKey ( arrow . Key ) )
103104 {
104- InputEventKey eventKey = new InputEventKey ( ) ;
105- eventKey . Keycode = ( Key ) Enum . Parse ( typeof ( Key ) , selectedScheme [ arrow . Key ] ) ;
106- InputMap . ActionAddEvent ( arrow . Key , eventKey ) ;
105+ string inputName = selectedScheme [ arrow . Key ] ;
106+
107+ if ( inputName . StartsWith ( "Joypad" ) ) // Controller input
108+ {
109+ InputEventJoypadButton eventJoypad = new InputEventJoypadButton ( ) ;
110+ eventJoypad . ButtonIndex = GetJoypadButton ( inputName ) ;
111+
112+ if ( eventJoypad . ButtonIndex != JoyButton . Invalid ) // Ensure it's valid
113+ {
114+ InputMap . ActionAddEvent ( arrow . Key , eventJoypad ) ;
115+ }
116+ else
117+ {
118+ GD . PrintErr ( $ "Invalid joypad button mapping: { inputName } ") ;
119+ }
120+ }
121+ else // Keyboard input
122+ {
123+ if ( Enum . TryParse ( inputName , out Key keycode ) ) // Check if valid keyboard key
124+ {
125+ InputEventKey eventKey = new InputEventKey ( ) ;
126+ eventKey . Keycode = keycode ;
127+ InputMap . ActionAddEvent ( arrow . Key , eventKey ) ;
128+ }
129+ else
130+ {
131+ GD . PrintErr ( $ "Invalid key mapping: { inputName } ") ;
132+ }
133+ }
107134 }
108135 }
109136 }
110137
138+ private JoyButton GetJoypadButton ( string action )
139+ {
140+ return action switch
141+ {
142+ "Joypad_Dpad_Up" => JoyButton . DpadUp ,
143+ "Joypad_Dpad_Down" => JoyButton . DpadDown ,
144+ "Joypad_Dpad_Left" => JoyButton . DpadLeft ,
145+ "Joypad_Dpad_Right" => JoyButton . DpadRight ,
146+ _ => JoyButton . Invalid , // Return an invalid button if unknown
147+ } ;
148+ }
149+
111150 public override void _Process ( double delta )
112151 {
113152 foreach ( var arrow in Arrows )
@@ -124,4 +163,25 @@ public override void _Process(double delta)
124163 }
125164 }
126165 }
166+
167+ public override void _Input ( InputEvent @event )
168+ {
169+ // Detect if a gamepad button is pressed
170+ if ( @event is InputEventJoypadButton || @event is InputEventJoypadMotion )
171+ {
172+ // Get the currently active control scheme
173+ string currentScheme = ( string ) ProjectSettings . GetSetting ( "game/input_scheme" ) ;
174+
175+ // Switch to "CONTROLLER" scheme if not already active
176+ if ( currentScheme != "CONTROLLER" )
177+ {
178+ GD . Print ( "Gamepad detected, switching to CONTROLLER scheme." ) ;
179+ ProjectSettings . SetSetting ( "game/input_scheme" , "CONTROLLER" ) ;
180+ ProjectSettings . Save ( ) ;
181+
182+ // Reload the control scheme to apply changes
183+ LoadControlScheme ( ) ;
184+ }
185+ }
186+ }
127187}
0 commit comments