Question

I'm trying to write bukkit plugin and one of the features I would like to add is when a player drops to Y level 8 or lower it runs a command on that player. My current case is I'd like to teleport them to other coordinates if they drop to Y level 8 or lower.

Is there a lite way of doing this without have a command run on every "move" event getting each players location then getting their y position then checking if it's less than 9? cause that seems like it would be a lot of work on the server if there are many people moving around.

Was it helpful?

Solution 2

You could always use the SyncRepeatingTask. Then loop through all online players and check if their Y coordinate value is less than 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)

Just make sure to put the above code in your onEnable(), or a method that's called when your plugin is enabled.

If you want to change the repeat time dynamically based on the online players, you could use:

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);
}

Then all you have to do is invoke runTeleportTask() in your onEnable() method.

OTHER TIPS

There is a simpler way to do this without using runnables. Simply use a PlayerMoveEvent.

@EventHandler 
public void onMove(PlayerMoveEvent event) {
    if (event.getPlayer().getLocation().getY() <= 8) {
        event.getPlayer().teleport(event.getPlayer().getLocation().add(0, 100, 0));
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top