extends Node # Autoloaded as "Settings", so any script can call e.g. Settings.save_settings(). # Keeps player settings (key bindings and volume) and saves them to a file so # they're remembered between play sessions. # user:// is a per-user folder Godot picks for save data. On Linux it's # ~/.local/share/godot/app_userdata/slime-platformer/ const SAVE_PATH = "user://settings.cfg" # Which input actions show up in the Controls tab. "pause" is left out on # purpose so the player can't lose the key that opens the menu. const REBINDABLE_ACTIONS = ["moveLeft", "moveRight", "moveUp", "moveDown", "jump"] # Audio bus names, as set up in the Audio tab at the bottom of the editor. const VOLUME_BUSES = ["Master", "Music", "SFX"] func _ready() -> void: load_settings() func save_settings() -> void: var config := ConfigFile.new() for action in REBINDABLE_ACTIONS: var keys := [] for event in InputMap.action_get_events(action): if event is InputEventKey: keys.append(event.physical_keycode) config.set_value("controls", action, keys) for bus in VOLUME_BUSES: config.set_value("audio", bus, get_volume(bus)) config.save(SAVE_PATH) func load_settings() -> void: var config := ConfigFile.new() # No save file yet (first launch), so just keep the defaults. if config.load(SAVE_PATH) != OK: return for action in REBINDABLE_ACTIONS: if config.has_section_key("controls", action): InputMap.action_erase_events(action) for keycode in config.get_value("controls", action): InputMap.action_add_event(action, make_key_event(keycode)) for bus in VOLUME_BUSES: set_volume(bus, config.get_value("audio", bus, 1.0)) # Replace one of an action's keys. index is which key it is in the action's list, # since actions can have more than one (like Left Arrow and A for moveLeft). # An index past the end of the list adds a new key instead. func rebind(action: String, index: int, keycode: Key) -> void: var events := InputMap.action_get_events(action) if index < events.size(): events[index] = make_key_event(keycode) else: events.append(make_key_event(keycode)) # Re-add everything so the keys stay in the same order. InputMap.action_erase_events(action) for event in events: InputMap.action_add_event(action, event) # Put every binding back to what's set in Project Settings > Input Map. func reset_controls() -> void: InputMap.load_from_project_settings() func make_key_event(keycode: Key) -> InputEventKey: var event := InputEventKey.new() # Physical keycodes go by key position, so WASD stays in the same spot on # non-QWERTY keyboards (like AZERTY). event.physical_keycode = keycode return event # Volume is linear: 0.0 is silent, 1.0 is full volume. func get_volume(bus: String) -> float: return AudioServer.get_bus_volume_linear(AudioServer.get_bus_index(bus)) func set_volume(bus: String, volume: float) -> void: AudioServer.set_bus_volume_linear(AudioServer.get_bus_index(bus), volume)