Skip to main content

keybinds

  • register from common code
  • callback for press, release, held tick (client or server)
  • track whether currently pressed (synced to server)

Normally you have to handle making packets to sync key presses to the server yourself if you want to actually effect the game state. WrapperLib can handle this for you.

Usage‚Äč

Start by creating a new KeybindWrapper instance.

  • The key's lang entry will be key.CATEGORY.NAME. The category will be created if it does not already exist, its lang entry will be key.categories.CATEGORY. In general I recommend making your CATEGORY be your mod id. Don't forget to add translations for these in your resource pack.
  • You can omit the GLFW key constant to make it unbound by default.
  • This can safely be done in your common mod initialization. It will not crash on dedicated servers.
public static final KeybindWrapper key = KeybindWrapper.of(NAME, CATEGORY, GLFW.GLFW_KEY_M)...;

Your keybind will automaticlly be added to vanilla's controls menu and players can rebind it to whatever they want.

The following methods can be chained to add behaviour to your key bind.

synced()‚Äč

This will cause the state of the key to be synced to the server. With this option enabled, the events below will fire on the logical server, as well as the logical client. You may want to use player.level.isClientSide() to check which side you're on.

onHeldTick(Consumer<Player> action)‚Äč

The action will be called every tick (20 times per second) while the player is holding the key.

onPress(Consumer<Player> action)‚Äč

The action will be called once when the player initially presses the key.

onRelease(Consumer<Player> action)‚Äč

The action will be called once when the player releases the key.

Opening a gui will cause this event to fire (and onHeldTick to stop firing) even if the player keeps holding down the key. They must exit the gui, release the key and press it again to trigger onPress (and resume onHeldTick).

Retrieve Key State‚Äč

If you want behaviour beyond the provided action callbacks, you can check whether a certain player has the key is pressed from your own code with key.isPressed(player).

  • When called from the logical client, it can only retrieve data for that client's player. Any other players will always return false. You can add your own packet to resync from the server to all clients if you need it but you probably don't.
  • When called from the logical server, if you have set KeybindWrapper#synced, it can retrieve data for any connected player.

Simple Example‚Äč

This will give the player the levitation effect while holding Z.

public void onInitialize() {
KeybindWrapper.of("float", MOD_ID, GLFW.GLFW_KEY_Z).synced()
.onHeldTick(player -> {
if (!player.level.isClientSide()) {
player.addEffect(new MobEffectInstance(MobEffects.LEVITATION, 20));
}
}).onRelease(player -> {
if (!player.level.isClientSide()) {
player.removeEffect(MobEffects.LEVITATION);
}
});
}