2016-04-09 87 views
3

所以我想在首次执行命令后,检查玩家在手中右键点击书本的时间。我试图让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. 
    } 
} 
+0

为什么要在多次运行的任务中注册事件侦听器?对于您想要听的每个事件,您只需要在侦听器中实现一个方法(每次事件触发时都会调用该方法,无需重复任务)。 –

+0

如果他们运行这个命令,我想检查他们是否正确点击一本书,直到他们确实点击了一本书 –

+0

好吧,这需要做不同的处理。活动只能注册一次。我会注册PlayerInteractEvent,并且每当玩家右键点击一本书时,将他们点击的时间和他们的名字插入到列表中。然后,每当玩家执行命令时,您可以检查他们最近是否右键点击该书。 –

回答

1

为了知道如果玩家运行的命令,你必须储存玩家的UUID地方。首先你创建一个Set<UUID>,它临时存储所有执行命令的玩家的所有唯一ID,所以当你看到一个玩家存储在这个集合中时,你知道他们执行了这个命令。 A 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