Advertisement
Zalgo2462

Simple Point Mover

Jan 26th, 2012
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. import java.awt.Point;
  2. import java.lang.Exception;
  3. import java.lang.Math;
  4. import java.lang.Thread;
  5.  
  6. public class Mover {
  7. private volatile Point start, end;
  8. private final Thread horizontalThread;
  9. private final Thread verticalThread;
  10. private volatile boolean doMove = false;
  11. private final long hRate, vRate;
  12.  
  13. public Mover (Point start, Point end, long time) {
  14. this.start = start;
  15. this.end = end;
  16.  
  17. int xDist = Math.abs(start.x - end.x);
  18. int yDist = Math.abs(start.y - end.y);
  19.  
  20. hRate = xDist != 0 ? Math.round(time / xDist) : -1;
  21. vRate = yDist != 0 ? Math.round(time / yDist) : -1;
  22.  
  23. horizontalThread = new MoverThread(false);
  24. verticalThread = new MoverThread(true);
  25. }
  26.  
  27. public Point getPoint() {
  28. return start;
  29. }
  30.  
  31. public void startMove() {
  32. doMove = true;
  33. if(!horizontalThread.isAlive()) {
  34. horizontalThread.start();
  35. }
  36. if(!verticalThread.isAlive()) {
  37. verticalThread.start();
  38. }
  39. }
  40.  
  41. public void stopMove() {
  42. doMove = false;
  43. }
  44.  
  45. public boolean isMoving() {
  46. return horizontalThread.isAlive() || verticalThread.isAlive();
  47. }
  48.  
  49. private class MoverThread extends Thread {
  50. final boolean vertical;
  51. final boolean positive;
  52.  
  53. public MoverThread(boolean vertical) {
  54. this.vertical = vertical;
  55. this.positive = vertical ? start.y < end.y : start.x < end.x;
  56. }
  57.  
  58. public void run() {
  59. while (doMove && (vertical ? start.y != end.y : start.x != end.x)) {
  60. start.move(!vertical ? positive ? start.x + 1 : start.x - 1 : start.x,
  61. vertical ? positive ? start.y + 1 : start.y - 1 : start.y);
  62. try {sleep(vertical ? vRate : hRate);} catch (Exception e) { System.out.println("Could not sleep");}
  63. }
  64. }
  65. }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement