注意:1.8.0 是 Modrinth 上可用的最后一个版本。新版本将继续在 GitHub 页面发布 .
PlayerAPI
一个客户端的 Fabric 库,为玩家交互、世界查询和类人自动化提供清晰的高级 API。旨在作为共享基础,使其他模组无需重新实现相同的低级 mixin。
对于玩家
PlayerAPI 本身不会执行任何操作。如果你下载了它,说明你使用的另一个模组将其作为依赖项。只需将该 .jar 文件与该模组一起放入你的 mods 文件夹中即可。
对于开发者
PlayerAPI — 设计与 API 参考
版本: 1.8.0
Minecraft: 1.21.11 (Fabric)
Maven 坐标: com.playerapi:playerapi:1.7.0
目录
- 概述与理念
- 架构
- 将 PlayerAPI 添加为依赖项
- 线程模型
- 事件 — PlayerAPIEvents
- 调度器
- 强制动作
- 人类动作
- 信息(只读查询)
- 数据类型
- 按键名称参考
- 已知限制
1. 概述与理念
PlayerAPI 是一个客户端 Fabric 库,为客户端自动化或实用模组所需的所有本地玩家操作提供了清晰、稳定的抽象层。它的存在是为了让消费模组永远不需要直接导入 Minecraft 内部代码——所有游戏交互都通过 PlayerAPI 的公共 API 类进行。
核心设计原则:
- 关注点分离。 每个 API 类都有单一明确的职责:信息类仅读取状态,动作类仅执行动作。绝不混合。
- 处处安全默认值。 每个读取玩家状态的方法,如果玩家不在世界中,都会返回安全默认值(
0、false、""、空列表、EMPTY 快照)。消费模组无需进行空值检查。
- 仅限主线程。 所有动作调用和事件回调都在主游戏线程上运行。无需管理并发。
- 强制 vs. 人类。 存在两个平行的动作系统。强制 动作是瞬间且精确到计算机级别的(适合精确定位)。人类 动作添加了反应延迟、弹簧物理视角插值和鼠标噪声(适合看起来更自然)。消费模组可根据用例选择适合的类型。
- 无内部状态泄露。 快照类型(
ItemSnapshot、EntitySnapshot、BlockSnapshot、EffectSnapshot)是不可变的 Java record。它们可以自由存储和比较,而不会导致底层游戏对象过时。
2. 架构
┌─────────────────────────────────────────────────────────┐
│ Consumer Mod │
│ (depends on PlayerAPI, never imports MC internals) │
└───────────────────┬─────────────────────────────────────┘
│ uses
┌───────────────────▼─────────────────────────────────────┐
│ PlayerAPI Public Surface │
│ │
│ Events Scheduler Actions (Forced) │
│ PlayerAPIEvents Scheduler MovementActions │
│ LookActions │
│ Info (read) InventoryActions │
│ PlayerInfo InteractionActions │
│ InventoryInfo ChatActions │
│ WorldInfo SoundActions │
│ TabListInfo DisplayActions │
│ │
│ Actions (Human) Data Types │
│ HumanActions ItemSnapshot │
│ HumanProfile EntitySnapshot │
│ BlockSnapshot │
│ EffectSnapshot │
└───────────────────┬─────────────────────────────────────┘
│ wraps
┌───────────────────▼─────────────────────────────────────┐
│ PlayerAPI Internals (not public) │
│ │
│ PlayerAPIMod — wires Fabric events, drives ticks │
│ KeyStateTracker — held-key set, mixin read target │
│ SchedulerState — tick-based task queue │
│ HumanLookState — spring-damper look interpolation │
│ MovementInputMixin — @Mixin(KeyboardInput) override │
│ PlayerInventoryAccessor — @Mixin accessor for slots │
└─────────────────────────────────────────────────────────┘
Tick 流程(每个游戏刻)
ClientTickEvents.END_CLIENT_TICK
│
├─ 1. SchedulerState.tick() — 触发已调度的任务
├─ 2. HumanLookState.tick() — 推进弹簧插值
├─ 3. diff-based event checks — 生命值、位置变化检测
└─ 4. PlayerAPIEvents.TICK.invoke() — 消费模组 tick 回调
按键覆盖机制
MovementInputMixin 是应用于 KeyboardInput 的 @Mixin,通过 TAIL 注入到其 tick() 方法中。在每个原版输入刻(tick)结束时,如果 KeyStateTracker.isActive() 为真,该 mixin 会用 KeyStateTracker 中存储的值覆盖 input.pressingForward、input.pressingBack、input.pressingLeft、input.pressingRight、input.jumping 和 input.sneaking。这意味着该覆盖对游戏其余部分完全透明——移动、冲刺物理效果以及服务器数据包均正常运作。
3. 添加 PlayerAPI 作为依赖项
build.gradle
repositories {
mavenLocal()
}
dependencies {
modImplementation "com.playerapi:playerapi:1.7.0"
}
gradle.properties
playerapi_version=1.7.0
fabric.mod.json
"depends": {
"playerapi": ">=1.7.0"
}
首先构建 PlayerAPI:
cd PlayerAPI
./gradlew publishToMavenLocal
然后正常构建你的模组。
4. 线程模型
所有 PlayerAPI 调用必须从主游戏线程发出。 这是运行 ClientTickEvents、渲染帧和处理网络数据包的线程。实际上这意味着:
- 在
PlayerAPIEvents.TICK 处理器内部 — ✅ 始终安全
- 在主线程上注册的 Fabric 事件处理器内部 — ✅ 安全
- 从后台线程或
CompletableFuture — ❌ 绝不安全;请使用 MinecraftClient.getInstance().execute(() -> ...) 进行 marshal 回主线程
Scheduler 总是在主线程上触发回调。
5. 事件 — PlayerAPIEvents
所有事件都位于 com.playerapi.PlayerAPIEvents。请从模组的 onInitializeClient() 中注册监听器。
PlayerAPIEvents.TICK.register(() -> {
// 每个刻运行一次
});
所有事件均使用 Fabric 的 EventFactory.createArrayBacked 模式——多个模组可以独立注册,且所有监听器都会触发。
TICK
Event<PlayerAPIEvents.Tick> TICK
在游戏每个刻触发一次,位于 END_CLIENT_TICK 之后,且在调度器处理完到期任务之后。
接口:
@FunctionalInterface
interface Tick {
void onTick();
}
备注:
- 这是任何每刻自动化逻辑的主要入口点。
- 如果你的逻辑需要已加载的世界,请在顶部调用
PlayerInfo.isInWorld()。
- 调度器在此事件触发之前运行,因此当你的
TICK 处理器运行时,从前一个刻调度的任务已经完成。
CHAT_RECEIVED
Event<PlayerAPIEvents.ChatReceived> CHAT_RECEIVED
当收到任何聊天消息时触发——包括玩家聊天、系统消息或游戏消息。涵盖已签名的玩家消息和未签名的服务器消息。
接口:
@FunctionalInterface
interface ChatReceived {
void onChatReceived(String sender, String message);
}
| 参数 |
描述 |
sender |
发送者的显示名称,已去除颜色代码。对于系统/游戏消息则为空字符串。 |
message |
完整消息文本,已去除颜色代码。 |
备注:
- 动作栏消息(
overlay=true)不会转发。
ClientReceiveMessageEvents.CHAT(玩家消息)和 ClientReceiveMessageEvents.GAME(系统/游戏消息)均汇入此单一事件。
HEALTH_CHANGED
Event<PlayerAPIEvents.HealthChanged> HEALTH_CHANGED
每当本地玩家的生命值发生任何数量变化时触发。
接口:
@FunctionalInterface
interface HealthChanged {
void onHealthChanged(float oldHealth, float newHealth);
}
备注:
- 如果生命值降至 0,则先触发
PLAYER_DEATH,随后立即触发 HEALTH_CHANGED。
- 不在加入世界时触发(初始生命值读取)。仅在第一次刻之后的变化时触发。
INVENTORY_CHANGED
Event<PlayerAPIEvents.InventoryChanged> INVENTORY_CHANGED
当玩家的主物品栏发生变化时触发。
接口:
@FunctionalInterface
interface InventoryChanged {
void onInventoryChanged(int slot, String newItemId);
}
| 参数 |
描述 |
slot |
发生变化的物品栏槽位。-1 表示批量/未知变化。 |
newItemId |
该槽位中新物品的命名空间 ID,例如 "minecraft:diamond_sword"。空槽位为 "minecraft:air"。 |
POSITION_CHANGED
Event<PlayerAPIEvents.PositionChanged> POSITION_CHANGED
当玩家相对于上次触发时的位置移动超过 0.1 格时触发。这是一个基于阈值的事件——它不会每个刻都触发,仅在有意义移动时触发。
接口:
@FunctionalInterface
interface PositionChanged {
void onPositionChanged(double x, double y, double z);
}
备注:
- 坐标为玩家脚部的位置。
- 0.1 格大致相当于正常渲染比例下的最小可见移动距离。
- 不适用于毫米级精度追踪——如需此类精度,请在
TICK 内部使用 PlayerInfo.getX/Y/Z()。
WORLD_JOIN
Event<PlayerAPIEvents.WorldJoin> WORLD_JOIN
在客户端连接到服务器或加载世界且玩家实体可用后触发一次。
接口:
@FunctionalInterface
interface WorldJoin {
void onWorldJoin();
}
备注:
- 加入世界时会重置生命值和位置差异状态,因此
HEALTH_CHANGED 和 POSITION_CHANGED 不会在第一个刻时无故触发。
- 在此事件触发时,
PlayerInfo.isInWorld() 返回 true。
WORLD_LEAVE
Event<PlayerAPIEvents.WorldLeave> WORLD_LEAVE
当客户端断开连接或离开世界时触发。所有按住的状态键会被释放,且任何活跃的人体视角插值都会在此事件触发前自动取消。
接口:
@FunctionalInterface
interface WorldLeave {
void onWorldLeave();
}
PLAYER_DEATH
Event<PlayerAPIEvents.PlayerDeath> PLAYER_DEATH
当玩家生命值降至 0 时触发。
接口:
@FunctionalInterface
interface PlayerDeath {
void onPlayerDeath();
}
备注:
HEALTH_CHANGED 也会紧接着触发,此时 newHealth = 0。
- 在触发此事件时,玩家实体仍然存在(死亡画面稍后才会出现)。
TAB_LIST_UPDATED
Event<PlayerAPIEvents.TabListUpdated> TAB_LIST_UPDATED
当服务器更新标签页(Tab)玩家列表时触发。频率限制为每游戏刻最多一次。
接口:
@FunctionalInterface
interface TabListUpdated {
void onTabListUpdated();
}
BLOCK_BROKEN
Event<PlayerAPIEvents.BlockBroken> BLOCK_BROKEN
当本地玩家成功破坏方块时触发。底层基于 Fabric 的 ClientPlayerBlockBreakEvents.AFTER。
接口:
@FunctionalInterface
interface BlockBroken {
void onBlockBroken();
}
备注:
- 即时破坏方块(作物、高草丛、花朵等)会在客户端立即触发,无需等待服务器确认。这对于自动化农场而言是最重要的情况。
- 生存模式下的方块(石头、木头等)会在服务器确认破坏后触发。
- 不会传递位置或方块类型信息。如果需要这些信息,请在
TICK 事件中提前读取 WorldInfo.getBlockAtCrosshair()。
6. 调度器 (Scheduler)
com.playerapi.Scheduler — 在主游戏线程上进行基于游戏刻的任务调度。
1 游戏刻 ≈ 20 TPS 时为 50 毫秒。
所有回调均为 Runnable,并在其到期的那一帧结束时于主游戏线程上触发。
schedule(int delayTicks, Runnable task) → int
安排任务在 delayTicks 个游戏刻后运行。返回一个取消令牌。
Scheduler.schedule(20, () -> doSomethingAfterOneSecond());
// token = 返回值,如果需要取消请保存它
delayTicks = 0 将在下一个游戏刻立即触发。
- 如果游戏因卡顿导致 TPS 低于 20,任务无法保证精确到每个游戏刻触发,但它们绝不会提前触发。
scheduleMs(long delayMs, Runnable task) → int
便捷重载方法。将毫秒数除以 50 转换为游戏刻数,并向上取整至最小值为 1。
Scheduler.scheduleMs(500, () -> doSomethingAfterHalfSecond());
scheduleRepeating(int periodTicks, int times, Runnable task) → int
安排重复执行的任务。
| 参数 |
描述 |
periodTicks |
每次调用之间的间隔游戏刻数。 |
times |
触发的次数。传入 0 表示无限次(直到被取消为止)。 |
task |
要运行的回调函数。 |
// 每秒触发一次,共触发 5 次:
Scheduler.scheduleRepeating(20, 5, () -> BotLogger.info("tick!"));
// 永久触发(无限循环 — 需手动取消):
int token = Scheduler.scheduleRepeating(20, 0, () -> doPeriodicCheck());
// 稍后:
Scheduler.cancel(token);
重要提示: 无限重复的任务在每次触发后会自动重新调度。取消初始令牌仅能阻止当前待触发的调用——如果任务已经触发过一次,若需要硬性取消,请使用 cancelAll() 或自行跟踪重新调度的令牌。
cancel(int token)
通过令牌取消待处理的任务。传入无效或已触发的令牌时调用也是安全的。
cancelAll()
取消使用此调度器的所有模组中的每一个待处理任务。在 stopBot() 中很有用,可确保停止后没有残留的延迟动作被触发。
getCurrentTick() → long
返回由 PlayerAPI 跟踪的当前全局刻数(tick count)。模组加载时从 0 开始,每经过一个 END_CLIENT_TICK 递增一次。可用于时间戳和速率限制。
long start = Scheduler.getCurrentTick();
// ...later...
long elapsed = Scheduler.getCurrentTick() - start; // 以刻为单位
double seconds = elapsed / 20.0;
7. 强制操作
强制操作是即时且精确到计算机层面的。它们会在下一个游戏刻立即生效,无延迟、无噪声或弹簧物理效果。当精度比外观更重要时使用这些功能。
7.1 MovementActions
控制玩家按住哪些移动键。仅在调用 setActive(true) 时,覆盖才生效。
有效的键名: "forward"、"back"、"left"、"right"、"sprint"、"sneak"、"jump"、"attack"、"use"
setActive(boolean active)
启用或禁用移动键覆盖。禁用时,所有按键将被释放,玩家恢复完全的手动控制。在按下任何键之前请先调用 setActive(true)。
MovementActions.setActive(true);
MovementActions.pressKey("forward");
MovementActions.pressKey("sprint");
// 玩家现在向前行走
isActive() → boolean
返回移动覆盖当前是否已启用。
pressKey(String key)
无限期按住某个键。该键将在后续每个刻保持按住状态,直到调用 releaseKey 或 releaseAll。
MovementActions.pressKey("jump"); // 按住空格键
releaseKey(String key)
释放之前按住的单个键。
MovementActions.releaseKey("sprint");
releaseAll()
释放当前按住的所有键(forward, back, left, right, sprint, sneak, jump, attack, use)。不会禁用覆盖——setActive 状态保持不变。
tapKey(String key, long durationMs)
按住键 durationMs 毫秒,然后自动释放。内部会转换为刻数。
MovementActions.tapKey("jump", 100); // 按住空格键 100 毫秒(2 刻)
pressKeys(Iterable<String> keys)
同时按下多个键。等同于对每个键依次调用 pressKey。
releaseDirectionKeys()
仅释放四个方向键(forward、back、left、right)。疾跑、潜行和跳跃状态保持不变。适用于在保持疾跑模式的同时停止移动。
getHeldKeys() → Set<String>
返回当前所有被按住按键名称的不可变快照。
isPressed(String key) → boolean
如果给定的键当前被覆盖持有,则返回 true。
randomDelay() → long
返回 50 ms 到 260 ms 之间的随机延迟。适用于在程序化按键之间作为时间抖动,以进行反模式检测。
7.2 LookActions
立即设置玩家摄像机方向。所有更改立即生效——没有动画效果。
Minecraft 偏航角(yaw)约定:
0° = 南 (+Z)
90° = 西 (−X)
180° = 北 (−Z)
270° = 东 (+X)
俯仰角(pitch): −90° = 垂直向上,0° = 水平,90° = 垂直向下。
setYaw(float yaw)
将玩家的水平旋转设置为精确的 yaw 度。
setPitch(float pitch)
将玩家的垂直旋转设置为精确的 pitch 度。自动钳制在 [−90, 90] 范围内。
lookAt(double x, double y, double z)
立即旋转以注视精确的世界坐标位置。根据玩家当前的眼睛位置自动计算所需的偏航角和俯仰角。
LookActions.lookAt(100.0, 64.0, -200.0);
// 用于整层瞄准:将 player.getY() + 1.62 作为 y 参数传入
lookAtBlock(int x, int y, int z)
立即注视方块的中心(x+0.5, y+0.5, z+0.5)。
lookAtBlock(BlockPos pos)
与上述相同,接受一个 BlockPos 参数。
lookAtBlock(int x, int y, int z, Direction face)
注视方块特定面的中心。face 是 Minecraft Direction 枚举值之一(UP, DOWN, NORTH, SOUTH, EAST, WEST)。
LookActions.lookAtBlock(10, 64, -5, Direction.UP); // 瞄准顶面
lookAtBlock(int x, int y, int z, double xOffset, double yOffset, double zOffset)
注视方块内的自定义点。偏移量是 [0, 1] 范围内的分数,其中 0.5, 0.5, 0.5 为方块中心。
LookActions.lookAtBlock(10, 64, -5, 0.5, 1.0, 0.5); // 顶面中心
snapToNearestCardinal()
将玩家的偏航角对齐到最接近的 90° 倍数。适用于在朝向基本方位的路径前进行对齐。
getSnappedYaw() → int
返回四舍五入到最近基本方位方向的当前偏航角(0、90、180 或 270)。
7.3 InventoryActions
直接操作物品栏。所有操作在下一个游戏刻立即生效。
switchToSlot(int slot)
将选中的快捷栏槽位切换为 slot(0–8)。如果 slot 超出范围,则无效。
switchToItem(String displayName) → boolean
切换到第一个名称完全匹配(不区分大小写)的物品所在的快捷栏槽位。如果找到并切换成功则返回 true,如果不在快捷栏中则返回 false。
InventoryActions.switchToItem("Wheat Hoe");
switchToItemStartingWith(String prefix) → boolean
切换到第一个显示名称以给定前缀开头(不区分大小写)的物品所在的快捷栏槽位。对于分层物品(如 "Pest Repellent I" / "Pest Repellent MAX")非常有用,当你只知道前缀时尤为方便。
InventoryActions.switchToItemStartingWith("Pest Repellent");
switchToItemId(String idSubstring) → boolean
切换到第一个命名空间 ID 包含 idSubstring(不区分大小写)的物品所在的快捷栏槽位。当物品名称被本地化或可能发生变化时,比按显示名称匹配更稳定。
InventoryActions.switchToItemId("diamond_hoe");
dropItem()
丢弃当前手持堆叠中的一个物品(相当于按下 Q 键)。
dropStack()
丢弃当前手持的整个物品堆叠(相当于按下 Ctrl+Q)。
dropAllInHotbar(String displayName)
遍历每个匹配 displayName 的快捷栏槽位,并丢弃其中的整个物品堆叠。之后恢复原始的选中槽位。
7.4 InteractionActions
玩家与物品、方块实体的交互。
useItem()
使用(右键点击)主手上的物品。向服务器发送适当的使用物品数据包。适用于消耗品、投掷物、放置方块、打开方块等。
useOffhandItem()
与 useItem() 相同,但用于副手槽位。
useItemHeld(long durationMs)
每隔一个游戏刻连续发送 useItem(),持续 durationMs 毫秒。适用于需要按住右键的物品(鱼竿、弓、充能弩)。
InteractionActions.useItemHeld(1500); // 按住右键 1.5 秒
attackTargeted()
攻击当前处于玩家准星下的实体(client.targetedEntity)。如果没有目标实体,则无操作。
attackBlockAtCrosshair()
对当前处于准星下的方块发送左键点击方块事件。每游戏刻调用一次可模拟按住左键挖掘方块。如果准星未对准方块,则无操作。
interactTargeted()
右键交互当前处于玩家准星下的实体(client.targetedEntity)。用于与 NPC 对话、骑乘实体等。
closeScreen()
关闭任何当前打开的屏幕(物品栏、容器、告示牌等)。相当于按下 Escape 键。
respawn()
向服务器发送重生请求。当玩家处于死亡屏幕时调用此方法以重生。
7.5 ChatActions
sendChat(String message)
代表玩家发送普通聊天消息。不要包含前导 /。
ChatActions.sendChat("Hello, world!");
sendCommand(String command)
发送不带前导斜杠的命令。PlayerAPI 会在内部添加斜杠前缀。
ChatActions.sendCommand("tp 0 64 0"); // 发送 /tp 0 64 0
ChatActions.sendCommand("warp garden"); // 发送 /warp garden
7.6 SoundActions
播放来自内置 Minecraft 声音库或你自己模组 .ogg 文件的声音。
浏览所有 Minecraft 声音 ID:
registerSound(String namespace, String name) → SoundEvent
注册一个新的声音事件。在 onInitializeClient() 期间调用一次。.ogg 文件必须位于模组资源 jar 包内的 assets/<namespace>/sounds/<name>.ogg 路径下。
SoundActions.registerSound("mymod", "my_alert"); // assets/mymod/sounds/my_alert.ogg
play(Identifier soundId, float volume, float pitch)
通过 Identifier 播放声音。适用于已注册的模组声音以及所有 Minecraft 内置声音。
| 参数 |
范围 |
描述 |
volume |
0.0 – 2.0 |
1.0 = 正常音量 |
pitch |
0.5 – 2.0 |
1.0 = 正常音高/速度 |
play(String namespace, String name, float volume, float pitch)
接受命名空间和名称作为独立字符串的便捷重载方法。
SoundActions.play("minecraft", "entity.player.levelup", 1.0f, 1.0f);
playById(String fullSoundId, float volume, float pitch)
通过完整的字符串 ID(如 "minecraft:entity.player.levelup")进行播放。如果未包含命名空间冒号,则默认为 "minecraft"。
SoundActions.playById("entity.experience_orb.pickup", 1.0f, 1.5f);
playRepeated(Identifier soundId, float volume, float pitch, int times, int intervalTicks)
以 intervalTicks 刻的间隔将声音播放 times 次。内部使用调度器(Scheduler)。
// 每间隔 1 秒播放升级声音 3 次:
Identifier id = Identifier.of("minecraft", "entity.player.levelup");
SoundActions.playRepeated(id, 1.0f, 1.0f, 3, 20);
playRepeated(Identifier soundId, float volume, float pitch, int times)
与上述方法相同,但固定为 20 刻(1 秒)的间隔。
playByIdRepeated(String fullSoundId, float volume, float pitch, int times, int intervalTicks)
playRepeated 方法的字符串 ID 便捷版本。
SoundActions.playByIdRepeated("minecraft:entity.player.levelup", 1.0f, 1.0f, 5, 20);
stopAll()
停止所有当前正在播放的声音。
7.7 DisplayActions
在游戏内显示 HUD 文本,无需直接依赖 Minecraft 内部机制。
showTitle(String title, String subtitle)
显示标题和可选副标题,使用默认时间设置(10 刻淡入 / 70 刻停留 / 20 刻淡出)。
支持 § 颜色代码。若要将任一参数留空,请传入 ""。
DisplayActions.showTitle("§aBot Started", "§7Primary path loaded");
showTitle(String title, String subtitle, int fadeInTicks, int stayTicks, int fadeOutTicks)
与上述方法相同,但使用自定义时间设置。
showActionBar(String message)
在动作栏(即快捷栏上方显示的文本行)显示简短消息。约 2 秒后消失。支持 § 颜色代码。
DisplayActions.showActionBar("§ePaused — waiting for repellent");
8. Human Actions
Human API 镜像了 Forced API,但增加了类似人类的缺陷:反应延迟、带有超调量的弹簧物理相机移动、随机运动结束噪声以及滚轮切换槽位。所有时间参数均可通过 HumanProfile 进行调整。
8.1 HumanActions
视角方法(平滑,弹簧物理)
所有视角方法都会启动向目标的弹簧阻尼插值。在开始移动之前存在一个可配置的反应延迟,相机向目标加速,自然产生超调,并 settles 在一个小的随机噪声偏移量上。如果弹簧运动过慢,3 秒看门狗会强制完成移动。
| 方法 |
描述 |
lookAt(float yaw, float pitch) |
平滑看向指定的偏航角/俯仰角组合。 |
lookAt(double x, double y, double z) |
平滑看向精确的世界坐标位置。 |
lookAt(int x, int y, int z) |
平滑看向方块中心(整数坐标)。 |
lookAt(BlockPos pos) |
平滑看向方块位置。 |
lookAt(int x, int y, int z, Direction face) |
平滑看向方块的特定面。 |
lookAt(BlockPos pos, Direction face) |
同上,使用 BlockPos。 |
lookAt(int x, int y, int z, double xOffset, double yOffset, double zOffset) |
平滑看向方块内的自定义点。 |
lookYaw(float yaw) |
仅改变偏航角,保持当前俯仰角。 |
lookPitch(float pitch) |
仅改变俯仰角,保持当前偏航角。 |
cancelLook() |
中止任何进行中的视角插值。视角保持在当前位置。 |
isLooking() → boolean |
当视角操作(包括反应延迟)处于活动状态时返回 true。 |
按键方法(含反应延迟)
| 方法 |
描述 |
pressKey(String key) |
在随机的 [reactionMin, reactionMax] 刻延迟后按住按键。 |
releaseKey(String key) |
在短暂的 [keyDelayMin, keyDelayMax] 刻延迟后释放按键。 |
tapKey(String key, int holdTicks) |
按下按键约 holdTicks 刻,按下和释放时均带有抖动。 |
pressKeys(String... keys) |
同时按下多个按键,所有按键均经过相同的反应延迟。 |
releaseAll() |
在 1–2 刻延迟后释放所有按键。 |
物品栏方法(含延迟和滚动浏览)
| 方法 |
描述 |
switchToSlot(int targetSlot) |
切换到快捷栏槽位,如果 HumanProfile.scrollThroughSlots 为 true,则可选择性地滚动经过中间槽位。 |
switchToItem(String displayName) |
切换到第一个匹配显示名称的物品,带有延迟。 |
switchToItemId(String idSubstring) |
切换到第一个匹配物品 ID 的物品,带有延迟。 |
交互方法(含延迟)
| 方法 |
描述 |
useItem() |
在主手使用物品,经过 [useItemDelayMin, useItemDelayMax] 刻延迟。 |
useOffhandItem() |
在主副手使用物品,经过相同的延迟。 |
attackTargeted() |
在反应延迟后攻击准星指向的实体。 |
interactTargeted() |
在反应延迟后与准星指向的实体进行交互。 |
复合序列
lookThenDo(double x, double y, double z, Runnable callback)
开始朝向世界坐标位置进行注视,待注视完全稳定后执行一次 callback。内部逻辑为每 tick 轮询 isLooking() 直至返回 false,随后触发回调。包含一个 3 秒的看门狗机制,超时后无论是否稳定均会强制触发回调,以防止挂起。
HumanActions.lookThenDo(100.0, 64.0, -200.0, () -> {
HumanActions.useItem(); // 仅在摄像机稳定后触发
});
重载方法:
lookThenDo(int x, int y, int z, Runnable callback) — 方块中心
lookThenDo(BlockPos pos, Runnable callback) — BlockPos
lookThenDo(BlockPos pos, Direction face, Runnable callback) — 方块面
lookThenDo(float yaw, float pitch, Runnable callback) — 原始偏航角/俯仰角
getProfile() → HumanProfile
返回共享的 HumanProfile 实例,用于读取或修改时间参数。
8.2 HumanProfile
com.playerapi.HumanProfile — 单例配置对象。所有字段均为 public,可随时修改。更改将在下一次 HumanActions 调用时生效。
HumanProfile p = HumanProfile.getInstance();
反应时间
| 字段 |
类型 |
默认值 |
描述 |
reactionMinTicks |
int |
2 (~100 ms) |
任何人类动作开始前的最小延迟。 |
reactionMaxTicks |
int |
5 (~250 ms) |
任何人类动作开始前的最大延迟。真实人类的平均反应时间为 200–300 ms。 |
每次操作时会在 [reactionMin, reactionMax] 范围内随机选择一个值。
注视 / 摄像机(弹簧阻尼模型)
| 字段 |
类型 |
默认值 |
描述 |
lookSpringK |
float |
0.30 |
弹簧常数。每 tick 添加到速度中的角度误差比例。数值越高,逼近速度越快。范围:0.15(慢)– 0.50(快)。 |
lookDamping |
float |
0.55 |
每 tick 的阻尼乘数。低于约 2·√K 的值会产生过冲。范围:0.4(弹性大)– 0.85(几乎无过冲)。当 K=0.30 时,临界阻尼约为 1.095。 |
lookMaxDegPerTick |
float |
35° |
每 tick 旋转速度的硬性上限。防止瞬间甩动。 |
lookNoiseMaxDeg |
float |
0.8° |
注视稳定后添加的随机噪声。模拟不精确性。 |
lookMaxSettleTicks |
int |
40 |
如果在此数量的 tick 后注视仍未稳定,则强制设定为目标角度。防止无限循环的看门狗机制。 |
微动(空闲手部震颤)
| 字段 |
类型 |
默认值 |
描述 |
enableMicroLook |
boolean |
false |
当为 true 时,在没有注视进行中时,每 tick 应用微小的随机摄像机晃动。 |
microLookChancePerTick |
float |
0.012 |
每 tick 发生微动的概率(≈ 每 4 秒一次)。 |
microLookMaxDeg |
float |
0.4° |
每次微动的最大偏航角变化。俯仰角为此值的一半。 |
按键时序
| 字段 |
类型 |
默认值 |
描述 |
keyDelayMinTicks |
int |
1 |
键指令与按键按下之间的最小延迟。 |
keyDelayMaxTicks |
int |
4 |
最大延迟。 |
tapHoldJitterTicks |
int |
3 |
添加到点击保持持续时间的额外随机 tick 数。 |
物品栏 / 滚动
| 字段 |
类型 |
默认值 |
描述 |
scrollThroughSlots |
boolean |
true |
当为 true 时,switchToSlot 会滚动经过中间槽位,而不是直接跳转。 |
scrollIntervalTicks |
int |
2 |
启用 scrollThroughSlots 时,每次滚动步骤之间的 tick 间隔。 |
交互时序
| 字段 |
类型 |
默认值 |
描述 |
useItemDelayMinTicks |
int |
1 |
使用物品动作触发前的最小延迟。 |
useItemDelayMaxTicks |
int |
3 |
最大延迟。 |
内置预设
HumanProfile.getInstance().applyFastPreset(); // 近乎即时,锐利的注视,最小噪声
HumanProfile.getInstance().applyCasualPreset(); // 缓慢的反应,弹性的注视,微动效果
HumanProfile.getInstance().resetDefaults(); // 恢复所有出厂默认值
| 预设 |
reactionMin |
reactionMax |
lookSpringK |
lookDamping |
enableMicroLook |
| Default |
2 |
5 |
0.30 |
0.55 |
false |
| Fast |
1 |
2 |
0.48 |
0.58 |
false |
| Casual |
3 |
7 |
0.20 |
0.50 |
true |
9. Info (只读查询)
Info 类提供对游戏状态的只读访问。它们从不修改任何内容。如果玩家不在世界中,所有方法均返回安全默认值。
9.1 PlayerInfo
查询本地玩家的状态。
位置与移动
| 方法 |
返回值 |
描述 |
getX() |
double |
玩家脚部 X 坐标。 |
getY() |
double |
玩家脚部 Y 坐标。 |
getZ() |
double |
玩家脚部 Z 坐标。 |
getEyeY() |
double |
玩家视线高度 Y (getY() + eyeHeight)。 |
getYaw() |
float |
水平旋转(角度,Minecraft 约定)。 |
getPitch() |
float |
垂直旋转(角度)。 |
getVelocityX/Y/Z() |
double |
各轴的速度,单位为块/tick。 |
isOnGround() |
boolean |
如果站在实心表面上则为 true。 |
isSprinting() |
boolean |
如果设置了疾跑标志则为 true。 |
isSneaking() |
boolean |
如果正在潜行/蹲下则为 true。 |
isSwimming() |
boolean |
如果处于游泳动画中则为 true。 |
isFlying() |
boolean |
如果处于创造模式飞行状态则为 true。 |
isCreativeFlightEnabled() |
boolean |
如果玩家拥有飞行能力(创造/旁观者模式)则为 true。 |
isSubmergedInWater() |
boolean |
如果完全浸没在水中则为 true。 |
isInLava() |
boolean |
如果接触岩浆则为 true。 |
生命值
| 方法 |
返回值 |
描述 |
getHealth() |
float |
当前生命值(通常为 0–20)。 |
getMaxHealth() |
float |
最大生命值。 |
getAbsorptionAmount() |
float |
吸收伤害值(黄心)的数量。 |
getFoodLevel() |
int |
饥饿值(0–20)。 |
getSaturation() |
float |
饱和度等级。 |
getAir() |
int |
剩余空气刻数(最大 300)。 |
getMaxAir() |
int |
最大空气刻数(通常为 300)。 |
经验值
| 方法 |
返回值 |
描述 |
getXpLevel() |
int |
当前经验等级。 |
getXpProgress() |
float |
升至下一等级的进度(0.0–1.0)。 |
getTotalXp() |
int |
累计总经验点数。 |
身份及其他信息
| 方法 |
返回值 |
描述 |
getName() |
String |
玩家的 Minecraft 用户名。 |
getUuid() |
String |
玩家的 UUID,以字符串形式返回。 |
getGameMode() |
String |
"SURVIVAL"、"CREATIVE"、"ADVENTURE"、"SPECTATOR" 或 "UNKNOWN"。 |
getHeldItem() |
ItemSnapshot |
主手物品的快照。 |
getOffhandItem() |
ItemSnapshot |
副手物品的快照。 |
getActiveEffects() |
List<EffectSnapshot> |
所有活跃的状态效果。 |
hasEffect(String idSubstring) |
boolean |
如果任何活跃效果的 ID 包含该子串(不区分大小写),则返回 True。 |
isInWorld() |
boolean |
如果玩家实体存在于已加载的世界中,则返回 True。建议在 tick 处理程序的顶部使用此方法作为守卫条件。 |
isScreenOpen() |
boolean |
如果有任何 GUI 界面打开(如背包、箱子、聊天等),则返回 True。 |
9.2 InventoryInfo
读取物品栏内容。绝不修改任何内容。
物品栏槽位布局:
| 范围 |
内容 |
| 0–8 |
快捷栏 |
| 9–35 |
主储物区 |
| 36 |
头部护甲槽 |
| 37 |
胸部护甲槽 |
| 38 |
腿部护甲槽 |
| 39 |
脚部护甲槽 |
| 40 |
副手槽 |
快捷栏
| 方法 |
返回值 |
描述 |
getSelectedSlot() |
int |
当前选中的快捷栏槽位(0–8)。 |
getHotbarSlot(int slot) |
ItemSnapshot |
某个快捷栏槽位的快照。 |
getHotbar() |
List<ItemSnapshot> |
全部 9 个快捷栏槽位的快照。 |
getHotbarSnapshot() |
List<ItemSnapshot> |
与 getHotbar() 相同。旨在通过 .equals() 进行比较以检测变化。 |
hasItemInHotbar(String displayName) |
boolean |
如果任何快捷栏槽位中有名称显示匹配的物品(不区分大小写的精确匹配),则返回 True。 |
hasItemIdInHotbar(String idSubstring) |
boolean |
如果任何快捷栏槽位中有 ID 包含该子串的物品,则返回 True。 |
findHotbarSlotByName(String displayName) |
int |
第一个匹配的槽位索引,若无则返回 -1。 |
findHotbarSlotById(String idSubstring) |
int |
按物品 ID 查找的第一个匹配槽位索引,若无则返回 -1。 |
完整物品栏
| 方法 |
返回值 |
描述 |
getMainSlot(int slot) |
ItemSnapshot |
任意 0–35 号槽位的快照。 |
getMainInventory() |
List<ItemSnapshot> |
全部 36 个主物品栏槽位。 |
countByName(String displayName) |
int |
在所有 36 个槽位中,名称显示匹配的物品总数。 |
countById(String idSubstring) |
int |
在所有 36 个槽位中,ID 包含该子串的物品总数。 |
hasEmptySlot() |
boolean |
如果至少有一个主物品栏槽位为空,则返回 True。 |
emptySlotCount() |
int |
主物品栏中空槽位的数量。 |
护甲与副手
| 方法 |
返回值 |
描述 |
getArmorSlot(int armorIndex) |
ItemSnapshot |
0=头部, 1=胸部, 2=腿部, 3=脚部。 |
getArmor() |
List<ItemSnapshot> |
按顺序排列的全部 4 个护甲槽位(头部 → 脚部)。 |
getOffhandItem() |
ItemSnapshot |
副手槽位(第 40 号槽位)。 |
9.3 WorldInfo
查询当前世界/维度。
维度
| 方法 |
返回值 |
描述 |
getDimensionId() |
String |
例如 "minecraft:overworld"、"minecraft:the_nether"。 |
isInOverworld() |
boolean |
|
isInNether() |
boolean |
|
isInEnd() |
boolean |
|
getServerAddress() |
String |
服务器的地址:端口,单人游戏为 "local",未连接时为 "none"。 |
isSinglePlayer() |
boolean |
如果是单人游戏或局域网联机,则返回 True。 |
isWorldLoaded() |
boolean |
如果客户端当前已加载世界,则返回 True。 |
时间
| 方法 |
返回值 |
描述 |
getTimeOfDay() |
long |
当前天内的刻数(0–24000)。白天从 0 开始,夜晚大约在 13000 开始。 |
getWorldAge() |
long |
世界的总年龄(以刻为单位,永不重置)。 |
isDay() |
boolean |
如果时间 < 13000,则返回 True。 |
isNight() |
boolean |
isDay() 的反转。 |
天气
| 方法 |
返回值 |
描述 |
isRaining() |
boolean |
|
isThundering() |
boolean |
|
方块
| 方法 |
返回值 |
描述 |
getBlockId(int x, int y, int z) |
String |
命名空间格式的方块 ID,例如 "minecraft:grass_block"。如果未加载则返回 "minecraft:air"。 |
getBlockIdRelative(int dx, dy, int dz) |
String |
相对于玩家脚部偏移位置的方块 ID。 |
isAir(int x, int y, int z) |
boolean |
如果该方块是空气,则返回 True。 |
getSkyLight(int x, int y, int z) |
int |
天空光照等级 0–15。 |
getBlockLight(int x, int y, int z) |
int |
方块光照等级 0–15。 |
getLight(int x, int y, int z) |
int |
天空光与方块光的最大值。 |
isChunkLoaded(int x, int z) |
boolean |
如果世界坐标 x,z 处的区块已加载,则返回 True。 |
getBiomeId() |
String |
玩家当前位置所在的生物群系 ID。 |
实体
| 方法 |
返回值 |
描述 |
getNearbyEntities(double radius) |
List<EntitySnapshot> |
玩家半径内的所有活体实体。不包含自身。使用包围盒搜索。 |
getNearbyPlayers(double radius) |
List<EntitySnapshot> |
半径内的其他玩家实体。 |
getNearbyEntitiesMatching(double radius, Predicate<EntitySnapshot> filter) |
List<EntitySnapshot> |
getNearbyEntities 的过滤版本。 |
getEntityAtCrosshair() |
Optional<EntitySnapshot> |
准星下的实体(Minecraft 的射线投射目标),若未命中则返回空。 |
getBlockAtCrosshair() |
Optional<BlockSnapshot> |
准星下的方块,若未命中则返回空。包含所有方块状态属性。 |
getEntityNbt(int entityId) |
Map<String, String> |
以扁平字符串映射形式表示的实体 NBT。目前返回空映射 — 参见已知限制。 |
方块扫描
// 查找 10 格范围内的所有小麦作物:
List<BlockSnapshot> wheat = WorldInfo.getNearbyBlocks(10.0, "minecraft:wheat");
// 自定义过滤器 — 仅成熟作物:
List<BlockSnapshot> matureWheat = WorldInfo.getNearbyBlocksMatching(10.0,
b -> b.blockId().equals("minecraft:wheat") && b.stateEquals("age", "7"));
性能: getNearbyBlocks 和 getNearbyBlocksMatching 会扫描整个球体。为避免掉帧,请保持半径 ≤ 32。扫描复杂度为 O(r³)。
9.4 TabListInfo
查询标签页玩家列表。服务器在标签页中使用显示名称来展示侧边栏信息(分数、状态文本等)。
所有方法均调用 MinecraftClient.getNetworkHandler().getPlayerList(),并在未连接时返回安全默认值。
关于文本剥离的说明: 标签页中的显示名称是 Minecraft Text 对象。getAllLines() 和搜索方法会剥离所有格式化代码(颜色、粗体等)并返回纯字符串。若要检查格式(例如检测删除线),请使用 isLineStrikethrough()。
getAllLines() → List<String>
返回所有标签页显示名称字符串,已剥离颜色代码。按分数(降序)然后按用户名排序。
getAllLinesRaw() → List<String>
返回所有标签页显示名称字符串。旨在用于原始检查,但请注意 Fabric 中的 Text.getString() 已经剥离了 § 样式的代码。主要用于与其他方法结合时迭代 PlayerListEntry 对象。
findLineWithPrefix(String prefix) → String
返回第一个以 prefix 开头的已剥离标签页行,若未找到则返回 null。
String line = TabListInfo.findLineWithPrefix("Area:");
// → "Area: Garden"
findLinesWithPrefix(String prefix) → List<String>
返回所有以 prefix 开头的已剥离行。
findLineContaining(String substring) → String
返回第一个包含 substring(不区分大小写)的已剥离标签页行,若未找到则返回 null。
String line = TabListInfo.findLineContaining("Alive:");
// → " Alive: 3 pests"
findLinesContaining(String substring) → List<String>
返回所有包含 substring(不区分大小写)的已剥离行。
isLineStrikethrough(String substring) → boolean
如果第一个包含 substring 的标签页行中任何文本段应用了删除线样式,则返回 true。使用 Text.visit() 遍历 Style 树 — 这是检测删除线的唯一可靠方法,因为 getString() 会剥离所有格式。
// 检测被禁用/划掉的行:
if (TabListInfo.isLineStrikethrough("Bonus Pest Chance:")) {
// 该行被划掉 → 奖励已禁用
}
extractValueAfterPrefix(String prefix) → String
查找第一个以 prefix 开头的行,并返回前缀后的文本(已修剪)。若未找到则返回 null。
String area = TabListInfo.extractValueAfterPrefix("Area:"); // → "Garden"
parseKeyValueLines(String... prefixes) → Map<String, String>
一次性提取多个键值对。返回一个前缀 → 值的映射(若未找到则为 null)。
Map<String, String> data = TabListInfo.parseKeyValueLines("Area:", " Alive:", " Repellent:");
String area = data.get("Area:");
String alive = data.get(" Alive:");
extractInt(String prefix) → int
查找前缀后的第一个整数。若未找到或无法解析,则返回 -1。
int pestCount = TabListInfo.extractInt(" Alive:"); // → 3
anyLineMatches(String regex) → boolean
如果任何已剥离的标签页行匹配给定的 Java 正则表达式,则返回 true。
玩家列表查询
| 方法 |
返回值 |
描述 |
getPlayerUsernames() |
List<String> |
标签页中所有玩家的 Minecraft 账户名称。 |
isPlayerOnline(String username) |
boolean |
如果标签页中存在该用户名的玩家(不区分大小写),则返回 true。 |
getPlayerCount() |
int |
标签页中条目的总数。 |
10. 数据类型
所有类型均为不可变的 Java record。它们可以安全地存储、在方法间传递,并使用 .equals() 进行比较。它们不持有对 Minecraft 对象的实时引用。
10.1 ItemSnapshot
com.playerapi.types.ItemSnapshot
record ItemSnapshot(
String itemId, // 命名空间 ID,例如 "minecraft:diamond_hoe"
String displayName, // 本地化显示名称,例如 "Diamond Hoe"
int count, // 堆叠数量
int damage, // 伤害/耐久度数值
boolean enchanted // 如果存在任何附魔则为 true
)
静态字段:
ItemSnapshot.EMPTY — 表示空/空气槽位。itemId = "minecraft:air",count = 0。
方法:
isEmpty() — 如果 itemId 为 "minecraft:air" 或 count == 0,则返回 true。
工厂方法:
ItemSnapshot.from(ItemStack stack) — 从实时物品堆栈创建。对于 null/空堆栈返回 EMPTY。
ItemSnapshot held = PlayerInfo.getHeldItem();
if (!held.isEmpty() && held.displayName().contains("锄头")) {
System.out.println("手持: " + held); // "小麦锄头 x1 [skyblock:wheat_hoe]"
}
10.2 EntitySnapshot
com.playerapi.types.EntitySnapshot
record EntitySnapshot(
int entityId, // 客户端实体 ID(非 UUID)
String typeId, // 命名空间实体类型,例如 "minecraft:zombie"
String displayName, // 显示名称(可能包含自定义名牌)
Vec3d position, // 世界坐标 (x, y, z)
float health, // 当前生命值(非 LivingEntity 为 0)
float maxHealth // 最大生命值(非 LivingEntity 为 0)
)
注意: entityId 是客户端整数 ID,而非 UUID。每次加入世界时都会变化。请勿在会话之间持久化实体 ID。
List<EntitySnapshot> nearby = WorldInfo.getNearbyEntities(16.0);
for (EntitySnapshot e : nearby) {
System.out.printf("%s at %.1f/%.1f/%.1f (%.0f/%.0f HP)%n",
e.displayName(), e.position().x, e.position().y, e.position().z,
e.health(), e.maxHealth());
}
10.3 BlockSnapshot
com.playerapi.types.BlockSnapshot
record BlockSnapshot(
int x,
int y,
int z,
String blockId, // 命名空间 ID,例如 "minecraft:wheat"
Map<String, String> blockState // 属性名 → 值,例如 {"age": "7"}
)
方法:
| 方法 |
描述 |
getState(String key) |
返回方块状态属性的值,若不存在则返回 null。 |
hasState(String key) |
如果该属性存在则返回 True。 |
stateEquals(String key, String value) |
如果属性值等于 value(不区分大小写)则返回 True。 |
Optional<BlockSnapshot> block = WorldInfo.getBlockAtCrosshair();
block.ifPresent(b -> {
System.out.println(b.blockId()); // "minecraft:wheat"
System.out.println(b.getState("age")); // "7"
System.out.println(b.stateEquals("age", "7")); // true (已成熟)
});
常见方块状态属性:
| 方块 |
键 |
值 |
| 小麦 / 胡萝卜 / 土豆 |
age |
"0" – "7" (7 = 完全成熟) |
| 甘蔗 |
(无状态;检查上方方块) |
— |
| 南瓜 / 西瓜茎 |
age |
"0" – "7" |
| 下界疣 |
age |
"0" – "3" |
| 任意原木/木板 |
axis |
"x", "y", "z" |
10.4 EffectSnapshot
com.playerapi.types.EffectSnapshot
record EffectSnapshot(
String effectId, // 命名空间 ID,例如 "minecraft:speed"
String displayName, // 本地化名称,例如 "Speed"
int amplifier, // 从 0 开始索引 (amplifier 0 = I 级)
int remainingTicks // 剩余刻数
)
方法:
level() — 返回 amplifier + 1(用于显示的从 1 开始索引)。
remainingSeconds() — 返回 remainingTicks / 20.0f。
for (EffectSnapshot e : PlayerInfo.getActiveEffects()) {
System.out.printf("%s %d — %.1fs remaining%n",
e.displayName(), e.level(), e.remainingSeconds());
}
boolean hasSpeed = PlayerInfo.hasEffect("speed");
11. 按键名称参考
用于 MovementActions、HumanActions.pressKey/releaseKey/tapKey:
| 按键名称 |
描述 |
"forward" |
W 键(向前行走) |
"back" |
S 键(向后行走) |
"left" |
A 键(向左横移) |
"right" |
D 键(向右横移) |
"sprint" |
左 Ctrl(疾跑修饰键) |
"sneak" |
左 Shift(潜行/蹲下) |
"jump" |
空格键 |
"attack" |
鼠标左键(破坏方块 / 攻击实体) |
"use" |
鼠标右键(使用物品 / 放置方块 / 交互) |
12. 已知限制
WorldInfo.getEntityNbt() — 未实现
getEntityNbt(int entityId) 始终返回空映射。底层的 entity.saveSelfNbt() API 在 Minecraft 1.21.x 中更改为需要 RegistryManager 参数,且正确的方法名需要通过 ./gradlew genSources 进行验证。这是一个暂定存根,将在未来版本中修复。
TabListInfo.getAllLinesRaw() — 与 getAllLines() 相同
尽管名称如此,getAllLinesRaw() 仍然使用 Text.getString(),这会剥离 § 样式的代码。如果需要格式化信息,请使用 isLineStrikethrough()。
Scheduler cancelAll() 是全局的
Scheduler.cancelAll() 会取消所有使用 PlayerAPI 的模组的任务,而不仅仅是调用者的任务。如果多个模组同时运行且其中一个调用了 cancelAll(),其他模组的计划任务也会被取消。请据此设计模组——如果其他模组可能依赖计划任务,请避免使用 cancelAll()。
scheduleRepeating() 配合 times=0 — 取消令牌仅覆盖首次调用
无限重复的任务在触发后会自行重新调度。由 scheduleRepeating(period, 0, task) 返回的令牌只能取消当前待处理的调用。如果任务在你取消之前触发,它将重新调度并继续运行。请在回调中使用共享标志来实现干净的无限循环取消:
boolean[] running = {true};
Scheduler.scheduleRepeating(20, 0, () -> {
if (!running[0]) return; // 有效停止循环
doSomething();
});
// 要停止:running[0] = false;
MovementActions 需要先调用 setActive(true)
在未先调用 setActive(true) 的情况下调用 pressKey() 无效。当未处于激活状态时,Mixin 会忽略按键状态跟踪器。始终在你的机器人启动方法中调用 setActive(true),并在停止方法中调用 setActive(false) / releaseAll()。
非即时破坏方块的破坏事件
PlayerAPIEvents.BLOCK_BROKEN 通过 ClientPlayerBlockBreakEvents.AFTER 触发。对于生存模式下需要按住才能挖掘的方块,这会在服务器确认后触发,而不是立即在客户端触发。对于即时破坏的方块(作物、花朵、高草),它会立即触发。
Notice Version 1.8.0 is the last version available on Modrinth. New versions will continue to be released on the GitHub page .
PlayerAPI
A client-side Fabric library that exposes a clean, high-level API for player interaction, world querying, and human-like automation. Designed to be a shared foundation so other mods don't have to reimplement the same low-level mixins.
For Players
PlayerAPI does nothing on its own. If you downloaded this, another mod you use requires it as a dependency. Simply place the .jar in your mods folder alongside that mod.
For Developers
PlayerAPI — Design & API Reference
Version: 1.8.0
Minecraft: 1.21.11 (Fabric)
Maven coordinate: com.playerapi:playerapi:1.7.0
Table of Contents
- Overview & Philosophy
- Architecture
- Adding PlayerAPI as a Dependency
- Threading Model
- Events — PlayerAPIEvents
- Scheduler
- Forced Actions
- Human Actions
- Info (Read-Only Queries)
- Data Types
- Key Names Reference
- Known Limitations
1. Overview & Philosophy
PlayerAPI is a client-side Fabric library that provides a clean, stable abstraction over everything a client-side automation or utility mod needs to do with the local player. It exists so that consumer mods never have to import Minecraft internals directly — all game interaction flows through PlayerAPI's public API classes.
Core design principles:
- Separation of concerns. Every API class has one clear responsibility: info classes only read state, action classes only perform actions. Nothing is mixed.
- Safe defaults everywhere. Every method that reads player state returns a safe default (
0, false, "", empty list, EMPTY snapshot) if the player is not in a world. Consumer mods never need null checks.
- Main-thread only. All action calls and event callbacks run on the main game thread. There is no concurrency to manage.
- Forced vs. Human. There are two parallel action systems. Forced actions are instant and computer-precise (good for precise positioning). Human actions add reaction delays, spring-physics look interpolation, and mouse noise (good for looking natural). Consumer mods choose which fits their use case.
- No internal state leaks. Snapshot types (
ItemSnapshot, EntitySnapshot, BlockSnapshot, EffectSnapshot) are immutable Java records. They can be stored and compared freely without the underlying game object becoming stale.
2. Architecture
┌─────────────────────────────────────────────────────────┐
│ Consumer Mod │
│ (depends on PlayerAPI, never imports MC internals) │
└───────────────────┬─────────────────────────────────────┘
│ uses
┌───────────────────▼─────────────────────────────────────┐
│ PlayerAPI Public Surface │
│ │
│ Events Scheduler Actions (Forced) │
│ PlayerAPIEvents Scheduler MovementActions │
│ LookActions │
│ Info (read) InventoryActions │
│ PlayerInfo InteractionActions │
│ InventoryInfo ChatActions │
│ WorldInfo SoundActions │
│ TabListInfo DisplayActions │
│ │
│ Actions (Human) Data Types │
│ HumanActions ItemSnapshot │
│ HumanProfile EntitySnapshot │
│ BlockSnapshot │
│ EffectSnapshot │
└───────────────────┬─────────────────────────────────────┘
│ wraps
┌───────────────────▼─────────────────────────────────────┐
│ PlayerAPI Internals (not public) │
│ │
│ PlayerAPIMod — wires Fabric events, drives ticks │
│ KeyStateTracker — held-key set, mixin read target │
│ SchedulerState — tick-based task queue │
│ HumanLookState — spring-damper look interpolation │
│ MovementInputMixin — @Mixin(KeyboardInput) override │
│ PlayerInventoryAccessor — @Mixin accessor for slots │
└─────────────────────────────────────────────────────────┘
Tick Flow (every game tick)
ClientTickEvents.END_CLIENT_TICK
│
├─ 1. SchedulerState.tick() — fires due scheduled tasks
├─ 2. HumanLookState.tick() — advances spring interpolation
├─ 3. diff-based event checks — health, position changes
└─ 4. PlayerAPIEvents.TICK.invoke() — consumer mod tick callbacks
Key Override Mechanism
MovementInputMixin is a @Mixin on KeyboardInput with a TAIL injection into its tick() method. At the end of every vanilla input tick, if KeyStateTracker.isActive() is true, the mixin overwrites input.pressingForward, input.pressingBack, input.pressingLeft, input.pressingRight, input.jumping, and input.sneaking with the values stored in KeyStateTracker. This means the override is completely transparent to the rest of the game — movement, sprint physics, and server packets all behave normally.
3. Adding PlayerAPI as a Dependency
build.gradle
repositories {
mavenLocal()
}
dependencies {
modImplementation "com.playerapi:playerapi:1.7.0"
}
gradle.properties
playerapi_version=1.7.0
fabric.mod.json
"depends": {
"playerapi": ">=1.7.0"
}
Build PlayerAPI first:
cd PlayerAPI
./gradlew publishToMavenLocal
Then build your mod normally.
4. Threading Model
All PlayerAPI calls must be made from the main game thread. This is the thread that runs ClientTickEvents, renders frames, and processes network packets. In practice this means:
- Inside
PlayerAPIEvents.TICK handlers — ✅ always safe
- Inside any Fabric event handler registered on the main thread — ✅ safe
- From a background thread or
CompletableFuture — ❌ never safe; use MinecraftClient.getInstance().execute(() -> ...) to marshal back
The Scheduler always fires callbacks on the main thread.
5. Events — PlayerAPIEvents
All events live on com.playerapi.PlayerAPIEvents. Register listeners from your mod's onInitializeClient().
PlayerAPIEvents.TICK.register(() -> {
// runs every tick
});
All events use Fabric's EventFactory.createArrayBacked pattern — multiple mods can register independently and all listeners fire.
TICK
Event<PlayerAPIEvents.Tick> TICK
Fires once per game tick, after END_CLIENT_TICK, after the scheduler has processed due tasks.
Interface:
@FunctionalInterface
interface Tick {
void onTick();
}
Notes:
- This is the primary entry point for any per-tick automation logic.
- Call
PlayerInfo.isInWorld() at the top if your logic requires a loaded world.
- The scheduler runs before this event fires, so tasks scheduled from a previous tick are already complete when your
TICK handler runs.
CHAT_RECEIVED
Event<PlayerAPIEvents.ChatReceived> CHAT_RECEIVED
Fires when any chat message arrives — player chat, system messages, or game messages. Covers both signed player messages and unsigned server messages.
Interface:
@FunctionalInterface
interface ChatReceived {
void onChatReceived(String sender, String message);
}
| Parameter |
Description |
sender |
Display name of the sender, stripped of colour codes. Empty string for system/game messages. |
message |
Full message text, stripped of colour codes. |
Notes:
- Action bar messages (
overlay=true) are not forwarded.
- Both
ClientReceiveMessageEvents.CHAT (player messages) and ClientReceiveMessageEvents.GAME (system/game messages) feed into this single event.
HEALTH_CHANGED
Event<PlayerAPIEvents.HealthChanged> HEALTH_CHANGED
Fires whenever the local player's health value changes by any amount.
Interface:
@FunctionalInterface
interface HealthChanged {
void onHealthChanged(float oldHealth, float newHealth);
}
Notes:
PLAYER_DEATH fires first if health dropped to 0, then HEALTH_CHANGED fires immediately after.
- Not fired on world join (initial health read). Only fires on changes after the first tick.
INVENTORY_CHANGED
Event<PlayerAPIEvents.InventoryChanged> INVENTORY_CHANGED
Fires when the player's main inventory changes.
Interface:
@FunctionalInterface
interface InventoryChanged {
void onInventoryChanged(int slot, String newItemId);
}
| Parameter |
Description |
slot |
Inventory slot that changed. -1 means a bulk/unknown change. |
newItemId |
Namespaced item ID of the new item in that slot, e.g. "minecraft:diamond_sword". "minecraft:air" for an empty slot. |
POSITION_CHANGED
Event<PlayerAPIEvents.PositionChanged> POSITION_CHANGED
Fires when the player moves more than 0.1 blocks from their position at the last firing. This is a threshold-based event — it does not fire every tick, only on meaningful movement.
Interface:
@FunctionalInterface
interface PositionChanged {
void onPositionChanged(double x, double y, double z);
}
Notes:
- Coordinates are the player's feet position.
- 0.1 blocks is roughly the minimum visible movement at normal render scale.
- Not suitable for millimetre-precision tracking — use
PlayerInfo.getX/Y/Z() inside TICK for that.
WORLD_JOIN
Event<PlayerAPIEvents.WorldJoin> WORLD_JOIN
Fires once after the client connects to a server or loads a world and the player entity is available.
Interface:
@FunctionalInterface
interface WorldJoin {
void onWorldJoin();
}
Notes:
- Health/position diff state is reset on world join, so
HEALTH_CHANGED and POSITION_CHANGED will not fire spuriously on the first tick.
PlayerInfo.isInWorld() returns true at the time this fires.
WORLD_LEAVE
Event<PlayerAPIEvents.WorldLeave> WORLD_LEAVE
Fires when the client disconnects or leaves a world. All held keys are released and any active human look interpolation is cancelled automatically before this event fires.
Interface:
@FunctionalInterface
interface WorldLeave {
void onWorldLeave();
}
PLAYER_DEATH
Event<PlayerAPIEvents.PlayerDeath> PLAYER_DEATH
Fires when the player's health reaches 0.
Interface:
@FunctionalInterface
interface PlayerDeath {
void onPlayerDeath();
}
Notes:
HEALTH_CHANGED also fires immediately after with newHealth = 0.
- The player entity still exists at the time this fires (the death screen appears later).
TAB_LIST_UPDATED
Event<PlayerAPIEvents.TabListUpdated> TAB_LIST_UPDATED
Fires when the server updates the tab-list player list. Throttled to at most once per tick.
Interface:
@FunctionalInterface
interface TabListUpdated {
void onTabListUpdated();
}
BLOCK_BROKEN
Event<PlayerAPIEvents.BlockBroken> BLOCK_BROKEN
Fires when the local player successfully breaks a block. Backed by Fabric's ClientPlayerBlockBreakEvents.AFTER.
Interface:
@FunctionalInterface
interface BlockBroken {
void onBlockBroken();
}
Notes:
- Instant-break blocks (crops, tall grass, flowers) fire immediately client-side without waiting for server confirmation. This is the most important case for farming automation.
- Survival-mode blocks (stone, wood, etc.) fire after the server confirms the break.
- No position or block type information is passed. If you need that, read
WorldInfo.getBlockAtCrosshair() from the TICK event just before.
6. Scheduler
com.playerapi.Scheduler — tick-based task scheduling on the main game thread.
1 tick ≈ 50 ms at 20 TPS.
All callbacks are Runnable and fire on the main game thread at the end of the tick they are due.
schedule(int delayTicks, Runnable task) → int
Schedule a task to run after delayTicks ticks. Returns a cancel token.
Scheduler.schedule(20, () -> doSomethingAfterOneSecond());
// token = return value, save it if you need to cancel
delayTicks = 0 fires on the very next tick.
- Tasks are not guaranteed exact-tick timing if the game is lagging below 20 TPS, but they will never fire early.
scheduleMs(long delayMs, Runnable task) → int
Convenience overload. Converts milliseconds to ticks by dividing by 50, rounded up to a minimum of 1.
Scheduler.scheduleMs(500, () -> doSomethingAfterHalfSecond());
scheduleRepeating(int periodTicks, int times, Runnable task) → int
Schedule a repeating task.
| Parameter |
Description |
periodTicks |
Ticks between each invocation. |
times |
Number of times to fire. Pass 0 for infinite (runs until cancelled). |
task |
The callback to run. |
// Fire 5 times, once per second:
Scheduler.scheduleRepeating(20, 5, () -> BotLogger.info("tick!"));
// Fire forever (infinite loop — cancel manually):
int token = Scheduler.scheduleRepeating(20, 0, () -> doPeriodicCheck());
// later:
Scheduler.cancel(token);
Important: Infinite repeating tasks self-reschedule after each firing. Cancelling the initial token only prevents the current pending invocation from firing — if the task has already fired once, use cancelAll() or track re-scheduled tokens yourself if you need hard cancellation.
cancel(int token)
Cancel a pending task by its token. Safe to call with an invalid/already-fired token.
cancelAll()
Cancel every pending task across all mods using this scheduler. Useful in stopBot() to ensure no lingering delayed actions fire after stopping.
getCurrentTick() → long
Returns the current global tick count as tracked by PlayerAPI. Starts at 0 on mod load and increments once per END_CLIENT_TICK. Useful for timestamps and rate-limiting.
long start = Scheduler.getCurrentTick();
// ...later...
long elapsed = Scheduler.getCurrentTick() - start; // in ticks
double seconds = elapsed / 20.0;
7. Forced Actions
Forced actions are instant and computer-precise. They take effect on the very next game tick with no delay, noise, or spring physics. Use these when precision matters more than appearance.
7.1 MovementActions
Controls which movement keys the player holds. The override only applies when setActive(true) has been called.
Valid key names: "forward", "back", "left", "right", "sprint", "sneak", "jump", "attack", "use"
setActive(boolean active)
Enable or disable the movement key override. When disabled, all keys are released and the player regains full manual control. Call setActive(true) before pressing any keys.
MovementActions.setActive(true);
MovementActions.pressKey("forward");
MovementActions.pressKey("sprint");
// player now walks forward
isActive() → boolean
Returns whether the movement override is currently enabled.
pressKey(String key)
Hold a key indefinitely. The key stays held on every subsequent tick until releaseKey or releaseAll is called.
MovementActions.pressKey("jump"); // holds space bar
releaseKey(String key)
Release a single previously held key.
MovementActions.releaseKey("sprint");
releaseAll()
Release all currently held keys (forward, back, left, right, sprint, sneak, jump, attack, use). Does not disable the override — setActive remains unchanged.
tapKey(String key, long durationMs)
Press a key for durationMs milliseconds then automatically release it. Internally converts to ticks.
MovementActions.tapKey("jump", 100); // tap space for 100 ms (2 ticks)
pressKeys(Iterable<String> keys)
Press multiple keys simultaneously. Equivalent to calling pressKey for each.
releaseDirectionKeys()
Release only the four directional keys (forward, back, left, right). Sprint, sneak, and jump states are unchanged. Useful for stopping movement while staying in sprint mode.
getHeldKeys() → Set<String>
Returns an immutable snapshot of all currently held key names.
isPressed(String key) → boolean
Returns true if the given key is currently being held by the override.
randomDelay() → long
Returns a random delay between 50 ms and 260 ms. Useful as a timing jitter between programmatic key presses for anti-pattern detection.
7.2 LookActions
Instantly set the player's camera direction. All changes take effect immediately — there is no animation.
Minecraft yaw convention:
0° = South (+Z)
90° = West (−X)
180° = North (−Z)
270° = East (+X)
Pitch: −90° = straight up, 0° = horizontal, 90° = straight down.
setYaw(float yaw)
Set the player's horizontal rotation to exactly yaw degrees.
setPitch(float pitch)
Set the player's vertical rotation to exactly pitch degrees. Automatically clamped to [−90, 90].
lookAt(double x, double y, double z)
Instantly rotate to look at an exact world position. Calculates the required yaw and pitch automatically from the player's current eye position.
LookActions.lookAt(100.0, 64.0, -200.0);
// For level aim: pass player.getY() + 1.62 as the y argument
lookAtBlock(int x, int y, int z)
Instantly look at the centre of a block (x+0.5, y+0.5, z+0.5).
lookAtBlock(BlockPos pos)
Same as above, accepting a BlockPos.
lookAtBlock(int x, int y, int z, Direction face)
Look at the centre of a specific face of a block. face is a Minecraft Direction enum value (UP, DOWN, NORTH, SOUTH, EAST, WEST).
LookActions.lookAtBlock(10, 64, -5, Direction.UP); // aim at top face
lookAtBlock(int x, int y, int z, double xOffset, double yOffset, double zOffset)
Look at a custom point within a block. Offsets are fractions in [0, 1] where 0.5, 0.5, 0.5 is the block centre.
LookActions.lookAtBlock(10, 64, -5, 0.5, 1.0, 0.5); // top-face centre
snapToNearestCardinal()
Snap the player's yaw to the nearest multiple of 90°. Useful for aligning before a cardinal-facing path.
getSnappedYaw() → int
Returns the current yaw rounded to the nearest cardinal direction (0, 90, 180, or 270).
7.3 InventoryActions
Direct inventory manipulation. All operations take effect instantly on the next tick.
switchToSlot(int slot)
Switch the selected hotbar slot to slot (0–8). Has no effect if slot is out of range.
switchToItem(String displayName) → boolean
Switch to the first hotbar slot whose item's display name matches exactly (case-insensitive). Returns true if found and switched, false if not in hotbar.
InventoryActions.switchToItem("Wheat Hoe");
switchToItemStartingWith(String prefix) → boolean
Switch to the first hotbar slot whose item display name starts with the given prefix (case-insensitive). Useful for tiered items like "Pest Repellent I" / "Pest Repellent MAX" where you only know the prefix.
InventoryActions.switchToItemStartingWith("Pest Repellent");
switchToItemId(String idSubstring) → boolean
Switch to the first hotbar slot whose item's namespaced ID contains idSubstring (case-insensitive). More stable than display name matching when item names are localised or can change.
InventoryActions.switchToItemId("diamond_hoe");
dropItem()
Drop one item from the currently held stack (Q key equivalent).
dropStack()
Drop the entire currently held stack (Ctrl+Q equivalent).
dropAllInHotbar(String displayName)
Switch to each hotbar slot matching displayName and drop the entire stack. Restores the original selected slot afterward.
7.4 InteractionActions
Player interactions with items, blocks, and entities.
useItem()
Use (right-click) the item in the main hand. Sends the appropriate use-item packet to the server. Works for consumables, throwables, placing blocks, opening blocks, etc.
useOffhandItem()
Same as useItem() but for the off-hand slot.
useItemHeld(long durationMs)
Continuously send useItem() every tick for durationMs milliseconds. Useful for items that require holding right-click (fishing rods, bows, charging crossbows).
InteractionActions.useItemHeld(1500); // hold right-click for 1.5 seconds
attackTargeted()
Attack the entity currently under the player's crosshair (client.targetedEntity). Does nothing if no entity is targeted.
attackBlockAtCrosshair()
Send a left-click-block event for the block currently under the crosshair. Call every tick to simulate holding left-click to mine a block. Does nothing if the crosshair is not targeting a block.
interactTargeted()
Right-click interact with the entity currently under the crosshair (client.targetedEntity). Used for talking to NPCs, riding entities, etc.
closeScreen()
Close any currently open screen (inventory, container, sign, etc.). Equivalent to pressing Escape.
respawn()
Send a respawn request to the server. Call this when the player is on the death screen to respawn.
7.5 ChatActions
sendChat(String message)
Send a regular chat message on behalf of the player. Do not include a leading /.
ChatActions.sendChat("Hello, world!");
sendCommand(String command)
Send a command without the leading slash. PlayerAPI prefixes the slash internally.
ChatActions.sendCommand("tp 0 64 0"); // sends /tp 0 64 0
ChatActions.sendCommand("warp garden"); // sends /warp garden
7.6 SoundActions
Play sounds from the built-in Minecraft sound library or from your own mod's .ogg files.
Browse all Minecraft sound IDs at:
registerSound(String namespace, String name) → SoundEvent
Register a new sound event. Call once during onInitializeClient(). The .ogg file must be at assets/<namespace>/sounds/<name>.ogg inside your mod's resources jar.
SoundActions.registerSound("mymod", "my_alert"); // assets/mymod/sounds/my_alert.ogg
play(Identifier soundId, float volume, float pitch)
Play a sound by its Identifier. Works for both registered mod sounds and all built-in Minecraft sounds.
| Parameter |
Range |
Description |
volume |
0.0 – 2.0 |
1.0 = normal volume |
pitch |
0.5 – 2.0 |
1.0 = normal pitch/speed |
play(String namespace, String name, float volume, float pitch)
Convenience overload accepting namespace and name as separate strings.
SoundActions.play("minecraft", "entity.player.levelup", 1.0f, 1.0f);
playById(String fullSoundId, float volume, float pitch)
Play by a full string ID such as "minecraft:entity.player.levelup". If no namespace colon is present, defaults to "minecraft".
SoundActions.playById("entity.experience_orb.pickup", 1.0f, 1.5f);
playRepeated(Identifier soundId, float volume, float pitch, int times, int intervalTicks)
Play a sound times times with intervalTicks ticks between each play. Uses the Scheduler internally.
// Play level-up sound 3 times, 1 second apart:
Identifier id = Identifier.of("minecraft", "entity.player.levelup");
SoundActions.playRepeated(id, 1.0f, 1.0f, 3, 20);
playRepeated(Identifier soundId, float volume, float pitch, int times)
Same as above with a fixed 20-tick (1 second) interval.
playByIdRepeated(String fullSoundId, float volume, float pitch, int times, int intervalTicks)
String-ID convenience version of playRepeated.
SoundActions.playByIdRepeated("minecraft:entity.player.levelup", 1.0f, 1.0f, 5, 20);
stopAll()
Stop all currently playing sounds.
7.7 DisplayActions
Show in-game HUD text without relying on Minecraft internals directly.
showTitle(String title, String subtitle)
Show a title and optional subtitle with the default timing (10 ticks fade-in / 70 ticks stay / 20 ticks fade-out).
Supports § colour codes. Pass "" for either parameter to leave it blank.
DisplayActions.showTitle("§aBot Started", "§7Primary path loaded");
showTitle(String title, String subtitle, int fadeInTicks, int stayTicks, int fadeOutTicks)
Same as above with custom timing.
showActionBar(String message)
Show a short message on the action bar — the line that appears above the hotbar. Disappears after approximately 2 seconds. Supports § colour codes.
DisplayActions.showActionBar("§ePaused — waiting for repellent");
8. Human Actions
The Human API mirrors the Forced API but adds human-like imperfection: reaction delays, spring-physics camera movement with overshoot, random end-of-movement noise, and scroll-wheel slot switching. All timing parameters are tunable through HumanProfile.
8.1 HumanActions
Look methods (smooth, spring-physics)
All look methods start a spring-damper interpolation toward the target. There is a configurable reaction delay before movement begins, the camera accelerates toward the target, naturally overshoots, and settles with a small random noise offset. A 3-second watchdog forces completion if the spring is too slow.
| Method |
Description |
lookAt(float yaw, float pitch) |
Smooth look to a yaw/pitch pair. |
lookAt(double x, double y, double z) |
Smooth look toward an exact world position. |
lookAt(int x, int y, int z) |
Smooth look at the centre of a block (integer coords). |
lookAt(BlockPos pos) |
Smooth look at a block position. |
lookAt(int x, int y, int z, Direction face) |
Smooth look at a specific face of a block. |
lookAt(BlockPos pos, Direction face) |
Same, with a BlockPos. |
lookAt(int x, int y, int z, double xOffset, double yOffset, double zOffset) |
Smooth look at a custom point within a block. |
lookYaw(float yaw) |
Change only yaw, keep current pitch. |
lookPitch(float pitch) |
Change only pitch, keep current yaw. |
cancelLook() |
Abort any in-progress look interpolation. View stays where it is. |
isLooking() → boolean |
Returns true while a look (including reaction delay) is active. |
Key methods (with reaction delay)
| Method |
Description |
pressKey(String key) |
Hold a key after a random [reactionMin, reactionMax] tick delay. |
releaseKey(String key) |
Release a key after a short [keyDelayMin, keyDelayMax] tick delay. |
tapKey(String key, int holdTicks) |
Tap a key for approximately holdTicks ticks, with jitter on both press and release. |
pressKeys(String... keys) |
Press multiple keys simultaneously, all after the same reaction delay. |
releaseAll() |
Release all keys after 1–2 ticks. |
Inventory methods (with delay and scroll-through)
| Method |
Description |
switchToSlot(int targetSlot) |
Switch to hotbar slot, optionally scrolling through intermediate slots if HumanProfile.scrollThroughSlots is true. |
switchToItem(String displayName) |
Switch to first matching display name, with delay. |
switchToItemId(String idSubstring) |
Switch to first matching item ID, with delay. |
Interaction methods (with delay)
| Method |
Description |
useItem() |
Use main-hand item after a [useItemDelayMin, useItemDelayMax] tick delay. |
useOffhandItem() |
Use off-hand item after the same delay. |
attackTargeted() |
Attack crosshair entity after a reaction delay. |
interactTargeted() |
Interact with crosshair entity after a reaction delay. |
Compound sequences
lookThenDo(double x, double y, double z, Runnable callback)
Start a human look toward the world position, then execute callback once the look has fully settled. Internally polls isLooking() every tick until false, then fires the callback. A 3-second watchdog fires the callback anyway to prevent hangs.
HumanActions.lookThenDo(100.0, 64.0, -200.0, () -> {
HumanActions.useItem(); // fires only after camera settles
});
Overloads:
lookThenDo(int x, int y, int z, Runnable callback) — block centre
lookThenDo(BlockPos pos, Runnable callback) — BlockPos
lookThenDo(BlockPos pos, Direction face, Runnable callback) — block face
lookThenDo(float yaw, float pitch, Runnable callback) — raw yaw/pitch
getProfile() → HumanProfile
Returns the shared HumanProfile instance for reading or changing timing parameters.
8.2 HumanProfile
com.playerapi.HumanProfile — a singleton configuration object. All fields are public and can be modified at any time. Changes take effect on the next HumanActions call.
HumanProfile p = HumanProfile.getInstance();
Reaction time
| Field |
Type |
Default |
Description |
reactionMinTicks |
int |
2 (~100 ms) |
Minimum delay before any human action begins. |
reactionMaxTicks |
int |
5 (~250 ms) |
Maximum delay before any human action begins. A real human averages 200–300 ms. |
A random value in [reactionMin, reactionMax] is chosen each time.
Look / camera (spring-damper)
| Field |
Type |
Default |
Description |
lookSpringK |
float |
0.30 |
Spring constant. Fraction of angular error added to velocity per tick. Higher = faster approach. Range: 0.15 (slow) – 0.50 (fast). |
lookDamping |
float |
0.55 |
Damping multiplier per tick. Values below ~2·√K produce overshoot. Range: 0.4 (bouncy) – 0.85 (barely any overshoot). Critical damping for K=0.30 is ≈1.095. |
lookMaxDegPerTick |
float |
35° |
Hard cap on rotational speed per tick. Prevents instant flicks. |
lookNoiseMaxDeg |
float |
0.8° |
Random noise added once the look settles. Simulates imprecision. |
lookMaxSettleTicks |
int |
40 |
If the look hasn't settled after this many ticks, it is forced to the exact target. Watchdog against infinite loops. |
Micro-movements (idle hand tremor)
| Field |
Type |
Default |
Description |
enableMicroLook |
boolean |
false |
When true, tiny random camera nudges apply every tick while no look is in progress. |
microLookChancePerTick |
float |
0.012 |
Probability per tick of a micro-movement firing (≈ once per 4 seconds). |
microLookMaxDeg |
float |
0.4° |
Maximum yaw change per micro-movement. Pitch is half this value. |
Key timing
| Field |
Type |
Default |
Description |
keyDelayMinTicks |
int |
1 |
Minimum delay between key command and key going down. |
keyDelayMaxTicks |
int |
4 |
Maximum delay. |
tapHoldJitterTicks |
int |
3 |
Extra random ticks added to a tap's hold duration. |
Inventory / scroll
| Field |
Type |
Default |
Description |
scrollThroughSlots |
boolean |
true |
When true, switchToSlot scrolls through intermediate slots rather than jumping directly. |
scrollIntervalTicks |
int |
2 |
Ticks between each scroll step when scrollThroughSlots is enabled. |
Interaction timing
| Field |
Type |
Default |
Description |
useItemDelayMinTicks |
int |
1 |
Minimum delay before a use-item action fires. |
useItemDelayMaxTicks |
int |
3 |
Maximum delay. |
Built-in presets
HumanProfile.getInstance().applyFastPreset(); // near-instant, snappy look, minimal noise
HumanProfile.getInstance().applyCasualPreset(); // slow reactions, bouncy look, micro-movements
HumanProfile.getInstance().resetDefaults(); // restore all factory defaults
| Preset |
reactionMin |
reactionMax |
lookSpringK |
lookDamping |
enableMicroLook |
| Default |
2 |
5 |
0.30 |
0.55 |
false |
| Fast |
1 |
2 |
0.48 |
0.58 |
false |
| Casual |
3 |
7 |
0.20 |
0.50 |
true |
9. Info (Read-Only Queries)
Info classes provide read-only access to game state. They never modify anything. All return safe defaults if the player is not in a world.
9.1 PlayerInfo
Query the local player's state.
Position & movement
| Method |
Returns |
Description |
getX() |
double |
Player feet X coordinate. |
getY() |
double |
Player feet Y coordinate. |
getZ() |
double |
Player feet Z coordinate. |
getEyeY() |
double |
Player eye-level Y (getY() + eyeHeight). |
getYaw() |
float |
Horizontal rotation (degrees, Minecraft convention). |
getPitch() |
float |
Vertical rotation (degrees). |
getVelocityX/Y/Z() |
double |
Per-axis velocity in blocks per tick. |
isOnGround() |
boolean |
True if standing on a solid surface. |
isSprinting() |
boolean |
True if the sprint flag is set. |
isSneaking() |
boolean |
True if sneaking/crouching. |
isSwimming() |
boolean |
True if in swim animation. |
isFlying() |
boolean |
True if creative flight is active. |
isCreativeFlightEnabled() |
boolean |
True if the player has fly ability (creative/spectator). |
isSubmergedInWater() |
boolean |
True if fully submerged. |
isInLava() |
boolean |
True if touching lava. |
Vitals
| Method |
Returns |
Description |
getHealth() |
float |
Current health points (typically 0–20). |
getMaxHealth() |
float |
Maximum health points. |
getAbsorptionAmount() |
float |
Absorption (yellow hearts) amount. |
getFoodLevel() |
int |
Hunger level (0–20). |
getSaturation() |
float |
Saturation level. |
getAir() |
int |
Remaining air ticks (max 300). |
getMaxAir() |
int |
Maximum air ticks (typically 300). |
Experience
| Method |
Returns |
Description |
getXpLevel() |
int |
Current XP level. |
getXpProgress() |
float |
Progress toward next level (0.0–1.0). |
getTotalXp() |
int |
Total accumulated XP points. |
Identity & misc
| Method |
Returns |
Description |
getName() |
String |
Player's Minecraft username. |
getUuid() |
String |
Player's UUID as a string. |
getGameMode() |
String |
"SURVIVAL", "CREATIVE", "ADVENTURE", "SPECTATOR", or "UNKNOWN". |
getHeldItem() |
ItemSnapshot |
Snapshot of the main-hand item. |
getOffhandItem() |
ItemSnapshot |
Snapshot of the off-hand item. |
getActiveEffects() |
List<EffectSnapshot> |
All active status effects. |
hasEffect(String idSubstring) |
boolean |
True if any active effect's ID contains the substring (case-insensitive). |
isInWorld() |
boolean |
True if the player entity exists in a loaded world. Use this as a guard at the top of tick handlers. |
isScreenOpen() |
boolean |
True if any GUI screen is open (inventory, chest, chat, etc.). |
9.2 InventoryInfo
Read inventory contents. Never modifies anything.
Inventory slot layout:
| Range |
Contents |
| 0–8 |
Hotbar |
| 9–35 |
Main storage |
| 36 |
Head armour |
| 37 |
Chest armour |
| 38 |
Leg armour |
| 39 |
Feet armour |
| 40 |
Off-hand |
Hotbar
| Method |
Returns |
Description |
getSelectedSlot() |
int |
Currently selected hotbar slot (0–8). |
getHotbarSlot(int slot) |
ItemSnapshot |
Snapshot of one hotbar slot. |
getHotbar() |
List<ItemSnapshot> |
Snapshots of all 9 hotbar slots. |
getHotbarSnapshot() |
List<ItemSnapshot> |
Identical to getHotbar(). Intended for change-detection by comparing with .equals(). |
hasItemInHotbar(String displayName) |
boolean |
True if any hotbar slot has an item matching the display name (case-insensitive exact match). |
hasItemIdInHotbar(String idSubstring) |
boolean |
True if any hotbar slot has an item whose ID contains the substring. |
findHotbarSlotByName(String displayName) |
int |
First matching slot index, or -1. |
findHotbarSlotById(String idSubstring) |
int |
First matching slot index by item ID, or -1. |
Full inventory
| Method |
Returns |
Description |
getMainSlot(int slot) |
ItemSnapshot |
Snapshot of any slot 0–35. |
getMainInventory() |
List<ItemSnapshot> |
All 36 main inventory slots. |
countByName(String displayName) |
int |
Total item count matching display name across all 36 slots. |
countById(String idSubstring) |
int |
Total item count matching ID substring across all 36 slots. |
hasEmptySlot() |
boolean |
True if at least one main inventory slot is empty. |
emptySlotCount() |
int |
Number of empty slots in the main inventory. |
Armour & off-hand
| Method |
Returns |
Description |
getArmorSlot(int armorIndex) |
ItemSnapshot |
0=head, 1=chest, 2=legs, 3=feet. |
getArmor() |
List<ItemSnapshot> |
All 4 armour slots in order (head → feet). |
getOffhandItem() |
ItemSnapshot |
Off-hand slot (slot 40). |
9.3 WorldInfo
Query the current world/dimension.
Dimension
| Method |
Returns |
Description |
getDimensionId() |
String |
e.g. "minecraft:overworld", "minecraft:the_nether". |
isInOverworld() |
boolean |
|
isInNether() |
boolean |
|
isInEnd() |
boolean |
|
getServerAddress() |
String |
Hostname:port of the server, "local" for singleplayer, "none" if not connected. |
isSinglePlayer() |
boolean |
True if singleplayer or LAN. |
isWorldLoaded() |
boolean |
True if a world is currently loaded client-side. |
Time
| Method |
Returns |
Description |
getTimeOfDay() |
long |
Ticks into the current day (0–24000). Day starts at 0, night at ~13000. |
getWorldAge() |
long |
Total world age in ticks (never resets). |
isDay() |
boolean |
True if time < 13000. |
isNight() |
boolean |
Inverse of isDay(). |
Weather
| Method |
Returns |
Description |
isRaining() |
boolean |
|
isThundering() |
boolean |
|
Blocks
| Method |
Returns |
Description |
getBlockId(int x, int y, int z) |
String |
Namespaced block ID, e.g. "minecraft:grass_block". Returns "minecraft:air" if unloaded. |
getBlockIdRelative(int dx, int dy, int dz) |
String |
Block ID at an offset from the player's feet. |
isAir(int x, int y, int z) |
boolean |
True if the block is air. |
getSkyLight(int x, int y, int z) |
int |
Sky light level 0–15. |
getBlockLight(int x, int y, int z) |
int |
Block light level 0–15. |
getLight(int x, int y, int z) |
int |
Max of sky and block light. |
isChunkLoaded(int x, int z) |
boolean |
True if the chunk at world coords x,z is loaded. |
getBiomeId() |
String |
Biome at the player's current position. |
Entities
| Method |
Returns |
Description |
getNearbyEntities(double radius) |
List<EntitySnapshot> |
All living entities within radius of the player. Excludes self. Uses a bounding-box search. |
getNearbyPlayers(double radius) |
List<EntitySnapshot> |
Other player entities within radius. |
getNearbyEntitiesMatching(double radius, Predicate<EntitySnapshot> filter) |
List<EntitySnapshot> |
Filtered version of getNearbyEntities. |
getEntityAtCrosshair() |
Optional<EntitySnapshot> |
Entity under the crosshair (Minecraft's raycast target), or empty. |
getBlockAtCrosshair() |
Optional<BlockSnapshot> |
Block under the crosshair, or empty. Includes all block-state properties. |
getEntityNbt(int entityId) |
Map<String, String> |
Entity NBT as a flat string map. Currently returns an empty map — see Known Limitations. |
Block scanning
// Find all wheat crops within 10 blocks:
List<BlockSnapshot> wheat = WorldInfo.getNearbyBlocks(10.0, "minecraft:wheat");
// Custom filter — mature crops only:
List<BlockSnapshot> matureWheat = WorldInfo.getNearbyBlocksMatching(10.0,
b -> b.blockId().equals("minecraft:wheat") && b.stateEquals("age", "7"));
Performance: getNearbyBlocks and getNearbyBlocksMatching scan a full sphere. Keep radius ≤ 32 to avoid frame drops. The scan is O(r³).
9.4 TabListInfo
Query the tab-list player list. Servers use display names in the tab list to show sidebar information (scores, status text, etc.).
All methods call MinecraftClient.getNetworkHandler().getPlayerList() and return safe defaults when not connected.
Note on text stripping: Display names in the tab list are Minecraft Text objects. getAllLines() and search methods strip all formatting codes (colours, bold, etc.) and return plain strings. To inspect formatting (e.g. detect strikethrough), use isLineStrikethrough().
getAllLines() → List<String>
Returns all tab-list display-name strings, stripped of colour codes. Ordered by score (descending) then by username.
getAllLinesRaw() → List<String>
Returns all tab-list display-name strings. Intended for raw inspection, though note that Text.getString() in Fabric already strips §-style codes. Useful primarily to iterate PlayerListEntry objects when combined with other methods.
findLineWithPrefix(String prefix) → String
Returns the first stripped tab-list line that starts with prefix, or null.
String line = TabListInfo.findLineWithPrefix("Area:");
// → "Area: Garden"
findLinesWithPrefix(String prefix) → List<String>
Returns all stripped lines starting with prefix.
findLineContaining(String substring) → String
Returns the first stripped tab-list line that contains substring (case-insensitive), or null.
String line = TabListInfo.findLineContaining("Alive:");
// → " Alive: 3 pests"
findLinesContaining(String substring) → List<String>
Returns all stripped lines containing substring (case-insensitive).
isLineStrikethrough(String substring) → boolean
Returns true if the first tab-list line containing substring has strikethrough styling applied to any of its text segments. Uses Text.visit() to walk the Style tree — the only reliable way to detect strikethrough since getString() strips all formatting.
// Detect a disabled/crossed-out line:
if (TabListInfo.isLineStrikethrough("Bonus Pest Chance:")) {
// line is crossed out → bonus is disabled
}
extractValueAfterPrefix(String prefix) → String
Find the first line starting with prefix and return the text after the prefix, trimmed. Returns null if not found.
String area = TabListInfo.extractValueAfterPrefix("Area:"); // → "Garden"
parseKeyValueLines(String... prefixes) → Map<String, String>
Extract multiple key-value pairs in one call. Returns a map of prefix → value (or null if not found).
Map<String, String> data = TabListInfo.parseKeyValueLines("Area:", " Alive:", " Repellent:");
String area = data.get("Area:");
String alive = data.get(" Alive:");
extractInt(String prefix) → int
Find the first integer after the prefix. Returns -1 if not found or not parseable.
int pestCount = TabListInfo.extractInt(" Alive:"); // → 3
anyLineMatches(String regex) → boolean
Returns true if any stripped tab-list line matches the given Java regex.
Player list queries
| Method |
Returns |
Description |
getPlayerUsernames() |
List<String> |
Minecraft account names of all players in the tab list. |
isPlayerOnline(String username) |
boolean |
True if a player with that username is in the tab list (case-insensitive). |
getPlayerCount() |
int |
Total number of entries in the tab list. |
10. Data Types
All types are immutable Java records. They are safe to store, pass between methods, and compare with .equals(). They hold no live references to Minecraft objects.
10.1 ItemSnapshot
com.playerapi.types.ItemSnapshot
record ItemSnapshot(
String itemId, // namespaced ID, e.g. "minecraft:diamond_hoe"
String displayName, // localised display name, e.g. "Diamond Hoe"
int count, // stack size
int damage, // damage/durability value
boolean enchanted // true if any enchantments are present
)
Static fields:
ItemSnapshot.EMPTY — represents an empty/air slot. itemId = "minecraft:air", count = 0.
Methods:
isEmpty() — true if itemId is "minecraft:air" or count == 0.
Factory:
ItemSnapshot.from(ItemStack stack) — create from a live stack. Returns EMPTY for null/empty stacks.
ItemSnapshot held = PlayerInfo.getHeldItem();
if (!held.isEmpty() && held.displayName().contains("Hoe")) {
System.out.println("Holding: " + held); // "Wheat Hoe x1 [skyblock:wheat_hoe]"
}
10.2 EntitySnapshot
com.playerapi.types.EntitySnapshot
record EntitySnapshot(
int entityId, // client-side entity ID (not UUID)
String typeId, // namespaced entity type, e.g. "minecraft:zombie"
String displayName, // display name (may include custom name tags)
Vec3d position, // world position (x, y, z)
float health, // current health (0 for non-LivingEntity)
float maxHealth // max health (0 for non-LivingEntity)
)
Note: entityId is the client-side integer ID, not the UUID. It changes on every world join. Do not persist entity IDs across sessions.
List<EntitySnapshot> nearby = WorldInfo.getNearbyEntities(16.0);
for (EntitySnapshot e : nearby) {
System.out.printf("%s at %.1f/%.1f/%.1f (%.0f/%.0f HP)%n",
e.displayName(), e.position().x, e.position().y, e.position().z,
e.health(), e.maxHealth());
}
10.3 BlockSnapshot
com.playerapi.types.BlockSnapshot
record BlockSnapshot(
int x,
int y,
int z,
String blockId, // namespaced ID, e.g. "minecraft:wheat"
Map<String, String> blockState // property name → value, e.g. {"age": "7"}
)
Methods:
| Method |
Description |
getState(String key) |
Returns the value of a block-state property, or null. |
hasState(String key) |
True if the property exists. |
stateEquals(String key, String value) |
True if the property value equals value (case-insensitive). |
Optional<BlockSnapshot> block = WorldInfo.getBlockAtCrosshair();
block.ifPresent(b -> {
System.out.println(b.blockId()); // "minecraft:wheat"
System.out.println(b.getState("age")); // "7"
System.out.println(b.stateEquals("age", "7")); // true (fully grown)
});
Common block state properties:
| Block |
Key |
Values |
| Wheat / Carrot / Potato |
age |
"0" – "7" (7 = fully grown) |
| Sugarcane |
(no state; check block above) |
— |
| Pumpkin / Melon stem |
age |
"0" – "7" |
| Nether Wart |
age |
"0" – "3" |
| Any log/plank |
axis |
"x", "y", "z" |
10.4 EffectSnapshot
com.playerapi.types.EffectSnapshot
record EffectSnapshot(
String effectId, // namespaced ID, e.g. "minecraft:speed"
String displayName, // localised name, e.g. "Speed"
int amplifier, // 0-indexed (amplifier 0 = Level I)
int remainingTicks // ticks remaining
)
Methods:
level() — returns amplifier + 1 (1-indexed for display).
remainingSeconds() — returns remainingTicks / 20.0f.
for (EffectSnapshot e : PlayerInfo.getActiveEffects()) {
System.out.printf("%s %d — %.1fs remaining%n",
e.displayName(), e.level(), e.remainingSeconds());
}
boolean hasSpeed = PlayerInfo.hasEffect("speed");
11. Key Names Reference
Used by MovementActions, HumanActions.pressKey/releaseKey/tapKey:
| Key Name |
Description |
"forward" |
W key (walk forward) |
"back" |
S key (walk backward) |
"left" |
A key (strafe left) |
"right" |
D key (strafe right) |
"sprint" |
Left Ctrl (sprint modifier) |
"sneak" |
Left Shift (sneak/crouch) |
"jump" |
Space bar |
"attack" |
Left mouse button (break block / attack entity) |
"use" |
Right mouse button (use item / place block / interact) |
12. Known Limitations
WorldInfo.getEntityNbt() — not implemented
getEntityNbt(int entityId) always returns an empty map. The underlying entity.saveSelfNbt() API changed in Minecraft 1.21.x to require a RegistryManager argument, and the correct method name needs verification via ./gradlew genSources. This is a stub pending a fix in a future version.
TabListInfo.getAllLinesRaw() — same as getAllLines()
Despite the name, getAllLinesRaw() still uses Text.getString() which strips §-style codes. Use isLineStrikethrough() when you need formatting information.
Scheduler cancelAll() is global
Scheduler.cancelAll() cancels tasks from all mods using PlayerAPI, not just the caller. If multiple mods are running simultaneously and one calls cancelAll(), the other's scheduled tasks are also cancelled. Design mods accordingly — avoid cancelAll() if other mods may be relying on scheduled tasks.
scheduleRepeating() with times=0 — cancel token only covers first invocation
Infinite repeating tasks self-reschedule after firing. The token returned by scheduleRepeating(period, 0, task) can only cancel the currently pending invocation. If the task fires before you cancel, it will reschedule itself and continue. Use a shared flag inside the callback to implement clean infinite-loop cancellation:
boolean[] running = {true};
Scheduler.scheduleRepeating(20, 0, () -> {
if (!running[0]) return; // effectively stops the loop
doSomething();
});
// To stop: running[0] = false;
MovementActions requires setActive(true) first
Calling pressKey() without calling setActive(true) first has no effect. The mixin ignores the key state tracker when not active. Always call setActive(true) in your bot's start method and setActive(false) / releaseAll() in the stop method.
Block break events on non-instant blocks
PlayerAPIEvents.BLOCK_BROKEN fires via ClientPlayerBlockBreakEvents.AFTER. For survival-mode blocks that require hold-to-mine, this fires after server confirmation, not immediately on the client. For instant-break blocks (crops, flowers, tall grass), it fires immediately.
评论 0
登录后参与评分
还没有评论,来抢沙发吧