我在使用 bukkit 可运行程序时遇到了一些问题。我试图让它工作,但它只会向我抛出错误。这就是我想要的
public class FlyE implements Listener {
@EventHandler
public void onPlayerMovement(PlayerMoveEvent e) {
Player p = e.getPlayer();
double y1 = p.getLocation().getY();
// wait 1 second
double y2 = p.getLocation().getY();
double yf = y1 - y2;
Bukkit.broadcastMessage(p + " Increase = " + yf);
}
}
这段代码的目的是获取用户的 Y 坐标,稍等一下,再次获取,然后计算出增量。然而,无论我如何尝试使用 BukkitRunnable,它都让我感到困惑。我希望有人能指导我如何将以下内容转换为 Bukkit Runnable,该 Bukkit Runnable 收集 y1,等待 20 个周期,然后收集 y2。
最佳答案
每次玩家移动时都会调用玩家移动事件。您只需要启动一次 Bukkit 调度程序,然后它就会持续运行。我不确定您想要如何选择播放器,因此这可能不完全是您想要实现的目标,但是一旦将其放入 onEnable() 方法中就启动调度程序。
public class MyPlugin extends JavaPlugin implements Listener {
private HashMap<String, Integer> lastY = new HashMap<>(); //Stores the last y location for an arbitrary number of users. The map key (String) is the user's name and the value (Integer) is the user's last Y coord
@Override
public void onEnable(){
//Start the timer asynchronously because it doesn't need to run on the main thread and the time will also be more accurate
Bukkit.getScheduler().runTaskTimerAsynchronously(this, new Runnable() {
@Override
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) { //Loop through all the players on the server
int y = player.getLocation().getBlockX();
player.sendMessage("Increase = " + (y - lastY.getOrDefault(player.getName(), 0))); //Display the increase in height using the stored value or 0 if none exists
lastY.put(player.getName(), y); //Replace their previous y coordinate with the new one
}
}
}, 0, 20L);
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent e){
lastY.remove(e.getPlayer().getName()); //Remove stored data for player
}
}
这里的 HashMap 允许您存储服务器上所有玩家的 y 坐标并以有效的方式访问它们。但是,请记住在不再需要时删除存储的数据(即玩家退出游戏)
关于java - Bukkit 等待/延迟帮助(Bukkit Runnable),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50564157/