Vector2d.java 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package classes;
  2. public class Vector2d {
  3. private float x;
  4. private float y;
  5. public Vector2d()
  6. {
  7. this.setX(0);
  8. this.setY(0);
  9. }
  10. public Vector2d(float x, float y)
  11. {
  12. this.setX(x);
  13. this.setY(y);
  14. }
  15. public void setX(float x) {
  16. this.x = x;
  17. }
  18. public float getX() {
  19. return x;
  20. }
  21. public void setY(float y) {
  22. this.y = y;
  23. }
  24. public float getY() {
  25. return y;
  26. }
  27. public void set(float x, float y)
  28. {
  29. this.setX(x);
  30. this.setY(y);
  31. }
  32. public float dot(Vector2d v2)
  33. {
  34. float result = 0.0f;
  35. result = this.getX() * v2.getX() + this.getY() * v2.getY();
  36. return result;
  37. }
  38. public float getLength()
  39. {
  40. return (float)Math.sqrt(getX()*getX() + getY()*getY());
  41. }
  42. public float getDistance(Vector2d v2)
  43. {
  44. return (float) Math.sqrt((v2.getX() - getX()) * (v2.getX() - getX()) + (v2.getY() - getY()) * (v2.getY() - getY()));
  45. }
  46. public Vector2d add(Vector2d v2)
  47. {
  48. Vector2d result = new Vector2d();
  49. result.setX(getX() + v2.getX());
  50. result.setY(getY() + v2.getY());
  51. return result;
  52. }
  53. public Vector2d subtract(Vector2d v2)
  54. {
  55. Vector2d result = new Vector2d();
  56. result.setX(this.getX() - v2.getX());
  57. result.setY(this.getY() - v2.getY());
  58. return result;
  59. }
  60. public Vector2d multiply(float scaleFactor)
  61. {
  62. Vector2d result = new Vector2d();
  63. result.setX(this.getX() * scaleFactor);
  64. result.setY(this.getY() * scaleFactor);
  65. return result;
  66. }
  67. public Vector2d normalize()
  68. {
  69. float len = getLength();
  70. if (len != 0.0f)
  71. {
  72. this.setX(this.getX() / len);
  73. this.setY(this.getY() / len);
  74. }
  75. else
  76. {
  77. this.setX(0.0f);
  78. this.setY(0.0f);
  79. }
  80. return this;
  81. }
  82. public String toString()
  83. {
  84. return "X: " + getX() + " Y: " + getY();
  85. }
  86. }