advanced cooldown?

Discussion in 'Spigot Plugin Development' started by Yazio, May 17, 2015.

  1. so i have my own plugin with a cooldown but i want try make it like when someone tries to do something while in cooldown i have seen a plugin say 4.7 seconds but... my only says 4 anyone that can help me?
     
  2. What have you tried so far?
     
  3. cooldownTime.put(player, getConfig().getInt("CooldownTime"));
     
  4. @T0X1C use longs and unix timestamps.
     
  5. Are you looking for something like that? Be careful, I didn't test it so much :p

    Code (Text):
    HashMap<Player, Long> lastUsage = new HashMap<Player, Long>();
        long cooldown = 4000L; //The cooldown value, taken from the config or hardcoded or whatever u want
        @EventHandler
        public void onQuit(PlayerQuitEvent e){
            lastUsage.remove(e.getPlayer()); //Clean up player information to avoid memory leaks
        }
        public long getLastUseMillis(Player player){ //Just a little function to ensure that a player will be always registered
                                                    // in the map
            Long last = lastUsage.get(player);
            if (last == null){
                last = 0L;
                lastUsage.put(player, last);
            }
            return last;
        }
        @EventHandler
        public void onUse(PlayerInteractEvent e){
            //Check whatever you want
            long last =  getLastUseMillis(e.getPlayer());
            if (System.currentTimeMillis() - last < cooldown){
                e.getPlayer().sendMessage(ChatColor.RED + String.format("Slow down! You have to wait %.1fs before using this item!"
                        , (cooldown - (System.currentTimeMillis() - last)) / 1000.0f));
            }
            else{
                lastUsage.put(e.getPlayer(), System.currentTimeMillis());
                //The player is allowed to use the item; do whatever u want to do here
                e.getPlayer().sendMessage(ChatColor.GREEN + "Great! You have used the item. Now WAIT HAHAHAHHA");
            }
        }
     
  6. Use a double and format it with Decimal Format #.#