Key Mappings

From Forge Community Wiki
Revision as of 22:29, 2 August 2021 by ChampionAsh5357 (talk | contribs) (Update to 1.17)

An input is required to produce some sort of action to the player within the game. These inputs can be boiled down to mappings associated with a certain key or mouse click. To allow these inputs to be remappable, a KeyMapping can be declared and registered.

A KeyMapping can be declared with the following parameters:

Parameter Description
name A translation key used to set the name of this key mapping (e.g. key.modid.key_name).
keyConflictContext Determines when the key mapping should conflict with another defined key mapping. By default, there are three values within KeyConflictContext: UNIVERSAL which are used in every context, GUI which are used whenever a screen is open, and IN_GAME whenever a screen is not open. Custom contexts can be created by implementing IKeyConflictContext.
key Determines the input context this mapping will declare by default. This is a combination of the input type, input code, and any additional modifiers. There are three possible values for the input type: KEYSYM which represents a mapped key, SCANCODE which represents the value emitted by the keyboard itself, and MOUSE which represents a mouse click. The associated input codes and modifiers are based on the specified input type as mapped by GLFW.
category A translation key representing the category this key is located in (e.g. key.modid.categories.category_name).
If you would like there to be no mapping by default, use a constructor that contains InputConstants$Key instead and supply InputConstants#UNKNOWN as the argument.

The KeyMapping can then be registered using ClientRegistry::registerKeyBinding within FMLClientSetupEvent.

Using Registered Mappings

There are two contexts in which a key mapping can be used normally: in or not in a screen. As such, there are two ways to handle these mappings. When not in a screen, ClientTickEvent should be used to determine whether the key is down using KeyMapping#isDown. If within a screen, the following logic can be applied using KeyMapping#isActiveAndMatches within GuiEventListener#keyPressed and GuiEventListener#mouseClicked for mouse input. Note that the necessary InputConstants$Key can be constructed using InputConstants::getKey or InputConstants$Type::getOrCreate respectively.