Code Patterns

Copy-paste examples for common plugin tasks. Commands, events, ECS, GUI, and more.

← Back to Patterns
command

Toggle Flight Command

Enable/disable player flight using MovementManager and MovementSettings. Based on working Simple Fly mod by davidhenk.

Example Code

java
public class FlyCommand extends CommandBase {

    public FlyCommand() {
        super("fly", "Toggle flying mode on or off");
    }

    @Override
    protected void executeSync(@Nonnull CommandContext context) {
        if (!context.isPlayer()) {
            context.sendMessage(Message.raw("Players only!"));
            return;
        }

        Ref<EntityStore> ref = context.senderAsPlayerRef();
        if (ref == null || !ref.isValid()) {
            context.sendMessage(Message.raw("Could not find player!"));
            return;
        }

        Store<EntityStore> store = ref.getStore();
        EntityStore entityStore = (EntityStore) store.getExternalData();
        World world = entityStore.getWorld();

        world.execute(() -> {
            if (!ref.isValid()) return;

            // Get MovementManager component
            MovementManager movementManager = store.getComponent(ref, MovementManager.getComponentType());
            if (movementManager == null) {
                context.sendMessage(Message.raw("Could not access movement!"));
                return;
            }

            // Toggle canFly
            MovementSettings settings = movementManager.getSettings();
            settings.canFly = !settings.canFly;

            // IMPORTANT: Sync to client!
            PlayerRef playerRef = store.getComponent(ref, PlayerRef.getComponentType());
            if (playerRef != null) {
                movementManager.update(playerRef.getPacketHandler());
            }

            // Feedback
            String msg = settings.canFly ? "Flight enabled! Double-tap jump." : "Flight disabled.";
            context.sendMessage(Message.raw(msg));
        });
    }
}

Thread Safety

Must call world.execute() to modify ECS. Must call movementManager.update() to sync to client.

Common Mistakes

Forgetting to call movementManager.update(packetHandler) - changes wont sync to client! Forgetting world.execute() - ECS changes must be on world thread.