2016-04-09 88 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