为了知道如果玩家运行的命令,你必须储存玩家的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。
为什么要在多次运行的任务中注册事件侦听器?对于您想要听的每个事件,您只需要在侦听器中实现一个方法(每次事件触发时都会调用该方法,无需重复任务)。 –
如果他们运行这个命令,我想检查他们是否正确点击一本书,直到他们确实点击了一本书 –
好吧,这需要做不同的处理。活动只能注册一次。我会注册PlayerInteractEvent,并且每当玩家右键点击一本书时,将他们点击的时间和他们的名字插入到列表中。然后,每当玩家执行命令时,您可以检查他们最近是否右键点击该书。 –