This is an old revision of the document!
Table of Contents
Custom Keybinds
Keybinds: straight from the keyboard
Minecraft handles user input from peripherals such as the keyboard & mouse using key-binds. When you press W your character moves forward, and when you press E your inventory opens. Every keybind can also be configured with the settings menu, so you can make your player move with arrow keys instead of WASD if you so desire.
Adding a key-bind is easy. You'll need to:
- create a KeyBinding object
- register your key
- react to the key being pressed
Creating your Keybind
Declare one of these in an area of your preference:
private static KeyBinding keyBinding;
FabricKeyBinding has a Builder for initialization. It takes in an Identifier, InputUtil.Type, key code, and binding category:
keyBinding = new KeyBinding( "key.examplemod.spook", // The translation key of the keybinding's name InputUtil.Type.KEYSYM, // The type of the keybinding, KEYSYM for keyboard, MOUSE for mouse. GLFW.GLFW_KEY_R, // The keycode of the key "category.examplemod.test" // The translation key of the keybinding's category. );
GLFW.GLFW_KEY_R can be replaced with whatever key you want the binding to default to. The category is related to how the keybinding is grouped in the settings page.
Configuring your Keybind's Category
Fabric will automatically register the keybinding's category on keybinding's registry.
Registering your Keybind
To register your keybinding, register using the KeyBindingHelper, in the client mod initializer:
KeyBindingHelper.registerKeyBinding(keyBinding);
If you log in to your game now, you will see your key binding in the settings page.
Responding to your Keybind
Unfortunately, there's no clear-cut way to respond to a keybinding. Most would agree the best way is to hook into the client tick event:
ClientTickCallback.EVENT.register(e -> { if(keyBinding.isPressed()) System.out.println("was pressed!"); });
Keep note that this is entirely client-side. To have the server respond to a keybind, you'll need to send a custom packet and have the server handle it separately.