如何使用Spigot API设置Minecraft村民实体路径至指定Location?
Spigot 1.21.1+ 让村民寻路到指定位置的解决方案
在1.21.1版本的Spigot API中,旧版的PathEntity相关寻路方法已被移除,目前需要通过NMS(Net Minecraft Server)的导航系统来实现实体寻路,以下是两种可行的实现方案:
方案一:直接调用导航系统移动
这种方式适合临时触发单次寻路需求,直接操控实体的导航模块前往目标位置:
import org.bukkit.Location; import org.bukkit.entity.LivingEntity; import org.bukkit.craftbukkit.v1_21_R1.entity.CraftLivingEntity; import net.minecraft.world.entity.ai.navigation.Navigation; import net.minecraft.core.BlockPos; public void moveVillagerToTarget(LivingEntity villager, Location target) { // 转换Bukkit实体为NMS实体 net.minecraft.world.entity.Entity nmsEntity = ((CraftLivingEntity) villager).getHandle(); // 获取实体的导航组件 Navigation navigation = nmsEntity.getNavigation(); // 转换Bukkit坐标为NMS BlockPos BlockPos targetPos = new BlockPos(target.getBlockX(), target.getBlockY(), target.getBlockZ()); // 启动寻路,最后一个参数为移动速度(村民原版速度约0.5) navigation.moveTo(targetPos.getX(), targetPos.getY(), targetPos.getZ(), 0.5D); }
方案二:通过AI目标系统实现持续寻路
如果需要让村民持续追踪目标位置(比如目标移动时自动更新路径),可以给村民添加专属的AI寻路目标:
import org.bukkit.Location; import org.bukkit.entity.Villager; import org.bukkit.craftbukkit.v1_21_R1.entity.CraftVillager; import net.minecraft.world.entity.npc.Villager; import net.minecraft.world.entity.ai.goal.PathfinderGoalMoveToLocation; // 添加寻路目标 public void addVillagerMoveGoal(Villager villager, Location target) { net.minecraft.world.entity.npc.Villager nmsVillager = ((CraftVillager) villager).getHandle(); // 创建移动目标:参数依次为实体、目标坐标、移动速度、寻路范围 PathfinderGoalMoveToLocation moveGoal = new PathfinderGoalMoveToLocation( nmsVillager, target.getX(), target.getY(), target.getZ(), 0.5D, 100 ); // 将目标加入AI列表,数值越小优先级越高(原版村民基础目标优先级多在5以上) nmsVillager.goalSelector.addGoal(1, moveGoal); } // 移除寻路目标 public void removeVillagerMoveGoal(Villager villager) { net.minecraft.world.entity.npc.Villager nmsVillager = ((CraftVillager) villager).getHandle(); nmsVillager.goalSelector.getAvailableGoals().removeIf( goal -> goal.getGoal() instanceof PathfinderGoalMoveToLocation ); }
注意事项
- 确保插件已正确引入
craftbukkit-1.21.1依赖,因为需要调用NMS相关类 - 村民的移动速度建议保持在0.3~0.6之间,避免偏离原版游戏体验
- 若需要自定义寻路规则(比如避开特定方块),可以使用
navigation.createPath(targetPos, 0)生成路径后,再调用navigation.moveTo(path)执行
内容的提问来源于stack exchange,提问作者Randall Arms
相关产品推荐
相关产品推荐

