AXHud

AXHud

为我的插件设计的HUD模组

基础库

AXHud

这个模组是为我的一些插件提供的 HUD 模组。

功能:

  • 目前该模组可以在用户屏幕顶部的物品旁边显示文本

命令

  • /axhud test diamond:测试显示
  • /axhud clear:清除显示

适用于:

你可以将此模组用于你自己的模组/插件。

查看方法 [Paper/Spigot 1.21.x]
package <your_package>;

import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class CommunicationInterface {
    private final JavaPlugin plugin;

    /**
     * 构造函数 - 传入你的插件实例
     *
     * 在你的主插件类中的用法:
     * 
     * public class <your_plugin> extends JavaPlugin {
     *     private CommunicationInterface commInterface;
     *
     *     @Override
     *     public void onEnable() {
     *         this.getServer().getMessenger().registerOutgoingPluginChannel(this, "axhud:display_item");
     *         this.commInterface = new CommunicationInterface(this);
     *     }
     *
     *     public CommunicationInterface getCommInterface() {
     *         return commInterface;
     *     }
     * }
     * 
     */
    public CommunicationInterface(JavaPlugin plugin) {
        this.plugin = plugin;
    }

    /**
     * 向玩家的客户端发送物品显示数据
     *
     * @param player 要发送到的玩家
     * @param itemId 物品 ID(例如 "minecraft:diamond"、"minecraft:emerald")
     * @param displayName 要在物品旁边显示的名称(支持颜色代码,如 §a、§b 等)
     */
    public void sendItemDisplay(Player player, String itemId, String displayName) {
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        DataOutputStream out = new DataOutputStream(byteStream);

        try {
            // 写入物品 ID 字符串
            writeString(out, itemId);

            // 写入显示名称字符串
            writeString(out, displayName);

            // 发送插件消息
            player.sendPluginMessage(plugin, "axhud:display_item", byteStream.toByteArray());
        } catch (IOException e) {
            plugin.getLogger().warning("Failed to send item display to player: " + e.getMessage());
        }
    }

    /**
     * 以 Minecraft 的格式将字符串写入 DataOutputStream
     * (VarInt 长度 + UTF-8 字节)
     */
    private void writeString(DataOutputStream out, String str) throws IOException {
        byte[] bytes = str.getBytes(java.nio.charset.StandardCharsets.UTF_8);
        writeVarInt(out, bytes.length);
        out.write(bytes);
    }

    /**
     * 将 VarInt 写入 DataOutputStream(Minecraft 协议格式)
     */
    private void writeVarInt(DataOutputStream out, int value) throws IOException {
        while ((value & 0xFFFFFF80) != 0) {
            out.writeByte((value & 0x7F) | 0x80);
            value >>>= 7;
        }
        out.writeByte(value & 0x7F);
    }
}