|
| 1 | +# This is an autoload (singleton) which will save |
| 2 | +# the key maps in a simple way through a dictionary. |
| 3 | +extends Node |
| 4 | + |
| 5 | +const keymaps_path = "user://keymaps.dat" |
| 6 | +var keymaps: Dictionary |
| 7 | + |
| 8 | + |
| 9 | +func _ready() -> void: |
| 10 | + # First we create the keymap dictionary on startup with all |
| 11 | + # the keymap actions we have. |
| 12 | + for action in InputMap.get_actions(): |
| 13 | + keymaps[action] = InputMap.get_action_list(action)[0] |
| 14 | + load_keymap() |
| 15 | + |
| 16 | + |
| 17 | +func load_keymap() -> void: |
| 18 | + var file := File.new() |
| 19 | + if not file.file_exists(keymaps_path): |
| 20 | + save_keymap() # There is no save file yet, so let's create one. |
| 21 | + return |
| 22 | + #warning-ignore:return_value_discarded |
| 23 | + file.open(keymaps_path, File.READ) |
| 24 | + var temp_keymap: Dictionary = file.get_var(true) |
| 25 | + file.close() |
| 26 | + # We don't just replace the keymaps dictionary, because if you |
| 27 | + # updated your game and removed/added keymaps, the data of this |
| 28 | + # save file may have invalid actions. So we check one by one to |
| 29 | + # make sure that the keymap dictionary really has all current actions. |
| 30 | + for action in keymaps.keys(): |
| 31 | + if temp_keymap.has(action): |
| 32 | + keymaps[action] = temp_keymap[action] |
| 33 | + # Whilst setting the keymap dictionary, we also set the |
| 34 | + # correct InputMap event |
| 35 | + InputMap.action_erase_events(action) |
| 36 | + InputMap.action_add_event(action, keymaps[action]) |
| 37 | + |
| 38 | + |
| 39 | +func save_keymap() -> void: |
| 40 | + # For saving the keymap, we just save the entire dictionary as a var. |
| 41 | + var file := File.new() |
| 42 | + #warning-ignore:return_value_discarded |
| 43 | + file.open(keymaps_path, File.WRITE) |
| 44 | + file.store_var(keymaps, true) |
| 45 | + file.close() |
0 commit comments