来自Override的ScheduledEvent Eventhandler

时间:2016-04-09 21:42:07

标签: java bukkit

所以我想先检查一下玩家在第一次执行命令后右键点击手中的书。我已尝试将Runnable作为计时器运行,并在该计划程序中检查玩家是否右手点击了手中的书。 Runnable强迫我改写' run'方法

这是我尝试过的:

@Override
public void onEnable() {

this.getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {

    @Override
    public void run() {
        //Here I want to check if the player right clicked with a book in their hand.
    }
}

1 个答案:

答案 0 :(得分:1)

为了知道玩家是否运行了命令,你必须将玩家的UUID存储在某个地方。首先,你创建一个Set<UUID>,它暂时存储执行命令的所有玩家的所有唯一ID,所以当你看到存储在这个集合中的玩家时,你知道他们执行了命令。 UUID是一个36个字符的字符串,对每个播放器都是唯一的,并且在每个服务器上都是相同的。你像这样Set

final Set<UUID> players = new HashSet<>();

接下来你需要做出命令。我会这样做:

@Override
public boolean onCommand(CommandSender sender, Command cmd, String cl, String[] args) {
    //Check if your command was executed
    if(cmd.getName().equalsIgnorecase("yourCommand")){
        //Check if the executor of the command is a player and not a commandblock or console
        if(sender instanceof Player){

            Player player = (Player) sender;

            //Add the player's unique ID to the set
            players.add(player.getUniqueId());
        } 
    }
}

现在你接下来要做的就是听PlayerInteractEvent看看玩家点击这本书的时间。如果你看到玩家在Set,你知道他们已经执行了命令。我将如何制作EventHandler

@EventHandler
public void onInteract(PlayerInteractEvent event){
    //Check if the player right clicked.
    if(event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK){
        //Check if the Set contains this player
        if(players.contains(event.getPlayer().getUniqueId()){
            //Check if the player had an item in their hand
            if(event.getPlayer().getItemInHand().getType() == Material.BOOK){
                //Remove player from the set so they have to execute the command again before right clicking the book again
                players.remove(event.getPlayer().getUniqueId());
                //Here you can do whatever you want to do when the player executed the command and right clicks a book.
            }
        }
    }
}

所以我所做的就是当玩家执行命令时,将它们存储在Set中。接下来听PlayerInteractEvent。这基本上是每次玩家交互时调用的回调方法。这可能是当玩家踏上压力板时,当玩家右手或左手点击障碍物或空中等时。

在那个PlayerInteractEvent中,我检查玩家是否存储在Set中,如果玩家右键单击一个区域并右键单击一个区块并检查玩家手中是否有一本书。如果这一切都正确,我会从Set中删除播放器,这样他们就必须再次执行命令才能执行相同的操作。

另外,不要忘记注册事件并实施Listener

如果您想了解有关Set的更多信息,可以找到Javadocs here

相关问题