Position.java 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package classes;
  2. import java.awt.Point;
  3. /**
  4. * Coordinates of an Object on the canvas with a (int) x-coord and a (int).
  5. * y-coord
  6. *
  7. * @author Gruppe14
  8. *
  9. */
  10. public class Position {
  11. /** Coordinate*/
  12. public int x,y;
  13. /**
  14. * Constructor with an positive x and y coord on the canvas.
  15. *
  16. * @param x Coord
  17. * @param y Coord
  18. */
  19. public Position(int x, int y) {
  20. this.x = x;
  21. this.y = y;
  22. }
  23. /**
  24. * Convert a Point to a Position;
  25. * @param p Point
  26. */
  27. public Position(Point p)
  28. {
  29. this.x = (int)p.getX();
  30. this.y = (int)p.getY();
  31. }
  32. public Position(Vector2d vector)
  33. {
  34. this.x = Math.round(vector.getX());
  35. this.y = Math.round(vector.getY());
  36. }
  37. /**
  38. * Default constructor without defined position.
  39. */
  40. public Position() {
  41. this.x = -1;
  42. this.y = -1;
  43. }
  44. /**
  45. * Return the Distance squared to a other Position.
  46. * Faster then Distance because no Sqrt() needed.
  47. * @param other the other Position.
  48. * @return squared distance to the Position
  49. */
  50. public double squareDistance(Position other)
  51. {
  52. //The Distance in X
  53. double xDis = x - other.x;
  54. //The Distance in Y
  55. double yDis = y - other.y;
  56. return xDis * xDis + yDis * yDis;
  57. }
  58. /**
  59. * Return the Distance to a other Position.
  60. * @param other the other Position.
  61. * @return distance to the Position.
  62. */
  63. public double Distance(Position other)
  64. {
  65. return Math.sqrt(squareDistance(other));
  66. }
  67. /**
  68. * Clamp the X Value two a upper or lower bound
  69. * @param min lower bound
  70. * @param max upper bound
  71. */
  72. public void clampX(int min, int max)
  73. {
  74. if(x < min) x = min;
  75. if(x > max) x = max;
  76. }
  77. /**
  78. * Clamp the Y Value two a upper or lower bound
  79. * @param min lower bound
  80. * @param max upper bound
  81. */
  82. public void clampY(int min, int max)
  83. {
  84. if(y < min) y = min;
  85. if(y > max) y = max;
  86. }
  87. /**
  88. * Returns a String that represents the value of this Position.
  89. * @return a string representation of this Position.
  90. */
  91. @Override
  92. public String toString() {
  93. return "Position[x=" + x + ",y="+ y +"]";
  94. }
  95. public Vector2d toVector() {
  96. return new Vector2d(x, y);
  97. }
  98. }