[RESOURCE] Class for no-move countdown actions

Discussion in 'Resources' started by NonameSL, Jun 20, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    NonameSL

    Here's an easy class I wrote down to countdown a teleport a player to a certain location, or just preform an action, or both.

    To cancel the teleportation, insert null instead of a location. To cancel the action, insert null instead of the runnable.


    Features:
    • Easy to use
    • Preform an action instead of a teleport, or even both!
    • Choose between cancel countdown on move or continue countown no matter what.
    • Cancel countdown manually whenever you want ( countdown.cancel(); )
    • Get how many seconds are left for the countdown
    Code:java
    1.  
    2.  
    3. import org.bukkit.Bukkit;
    4. import org.bukkit.Location;
    5. import org.bukkit.entity.Player;
    6. import org.bukkit.plugin.Plugin;
    7.  
    8. public class Countdown {
    9. private Location loc;
    10. private Player p;
    11. private double secs;
    12. private int taskID;
    13. private double count;
    14. private boolean cancelOnMove;
    15. private Runnable onFinish;
    16. private boolean compareLocation(Location l1, Location l2){
    17. return l1.getX()==l2.getX()&&l1.getY()==l2.getY()&&l1.getZ()==l2.getZ()&&l1.getYaw()==l2.getYaw()&&l1.getPitch()==l2.getPitch();
    18. }
    19. public Countdown(Plugin pl, Player player, double seconds, Location teleport, boolean cancelMove, Runnable onCountdown){
    20. this.p=player;
    21. this.onFinish=onCountdown;
    22. this.cancelOnMove=cancelMove;
    23. this.secs=seconds;
    24. this.loc=teleport;
    25. taskID = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(pl, new Runnable(){
    26. @Override
    27. public void run() {
    28. if(loc!=null)if(compareLocation(loc,p.getLocation())&&cancelOnMove){
    29. p.sendMessage("§cYou moved! Teleportation failed.");
    30. Bukkit.getServer().getScheduler().cancelTask(taskID);
    31. }
    32. if(count>=secs){
    33. p.teleport(loc);
    34. count=0;
    35. onFinish.run();
    36. Bukkit.getServer().getScheduler().cancelTask(taskID);
    37. }
    38. count+=0.1;
    39. }
    40.  
    41. }, 2L, 2L);
    42. }
    43. public double getSecondsLeft(){
    44. return secs-count;
    45. }
    46. public void cancel(){
    47. Bukkit.getServer().getScheduler().cancelTask(taskID);
    48. }
    49.  
    50.  

    If the non-spacing bothers you, enter pastebin here because bukkit forums cancels the spacing: http://pastebin.com/KiyjTivF
    Usage example:
    Code:java
    1. Runnable runnable = new Runnable(){
    2. @Override
    3. public void run(){
    4. p.sendMessage(ChatColor.DARK_RED+"You have been teleported!");
    5. }
    6. };
    7. Countdown countdown = new Countdown(this, p, 3.0, p.getLocation(), true, runnable);

    You're welcome!
     
Thread Status:
Not open for further replies.

Share This Page