如何检测玩家是否低于某个Y级别

时间:2014-05-07 18:29:09

标签: bukkit

我正在尝试编写bukkit插件,我想添加的功能之一是当玩家降至Y级别8或更低时,它会在该玩家上运行命令。我目前的情况是,如果它们降到Y级别8或更低,我想将它们传送到其他坐标。

有没有一种简单的方法可以在每次“移动”事件中运行命令,然后获取每个玩家的位置,然后获取他们的y位置,然后检查它是否小于9?因为如果有很多人四处走动,似乎在服务器上会有很多工作。

2 个答案:

答案 0 :(得分:2)

有一种更简单的方法可以在不使用runnable的情况下执行此操作。只需使用PlayerMoveEvent。

@EventHandler 
public void onMove(PlayerMoveEvent event) {
    if (event.getPlayer().getLocation().getY() <= 8) {
        event.getPlayer().teleport(event.getPlayer().getLocation().add(0, 100, 0));
    }
}

答案 1 :(得分:1)

您可以随时使用SyncRepeatingTask。然后遍历所有在线玩家并检查他们的Y坐标值是否小于9:

plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
    public void run() {
        for (Player player: Bukkit.getOnlinePlayers()) { // Loops through all online players
            if (player.getLocation().getY() < 9) {
                // The player's Y is below 9. Do whatever you want here. For example:
                player.teleport(player.getLocation().add(0, 100, 0)); // Teleports the player 100 blocks above where they are
            }
        }
    }
}, 50L, 50L); // Run every 2.5 seconds (50 ticks)

只需确保将上述代码放入onEnable(),或启用插件时调用的方法。

如果您想根据在线玩家动态更改重复时间,可以使用:

public void runTeleportTask() {

    long time = Math.round(Bukkit.getServer().getOnlinePlayers().length / 10) + 10;

    /*
        Tweak the delay however you like, above we get the online players, and divide it by 10 then
        add ten. We're adding 10 because you don't want to end up with a task that runs every
        tick in this case... The fastest it would be needed would be every 10 ticks.
        So if there were 100 players online, it would get 100/10 = 10, 10+10 = 20 = 1 second,
        and if there were 250 players online, it would get 250/10 = 25, 25 + 10 = 35 = 1.75 seconds
    */

    plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
        public void run() {
            for (Player player : Bukkit.getOnlinePlayers()) {
                if (player.getLocation().getY() < 9) {
                    player.teleport(player.getLocation().add(0, 100, 0));
                }
            }
            runTeleportTask();
        }
    }, time);
}

然后,您只需在runTeleportTask()方法中调用onEnable()