You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

vec2.js 947B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. export default class Vec2 {
  2. constructor(x, y) {
  3. this.x = x;
  4. this.y = y;
  5. }
  6. length() {
  7. return Math.sqrt((this.x * this.x) + (this.y * this.y));
  8. }
  9. clone() {
  10. return new Vec2(this.x, this.y);
  11. }
  12. set(x, y) {
  13. if (x instanceof Vec2)
  14. return this.set(x.x, x.y);
  15. this.x = x;
  16. this.y = y;
  17. return this;
  18. }
  19. add(x, y) {
  20. if (x instanceof Vec2)
  21. return this.add(x.x, x.y);
  22. this.x += x;
  23. this.y += y;
  24. return this;
  25. }
  26. sub(x, y) {
  27. if (x instanceof Vec2)
  28. return this.sub(x.x, x.y);
  29. this.x -= x;
  30. this.y -= y;
  31. return this;
  32. }
  33. scale(num) {
  34. this.x *= num;
  35. this.y *= num;
  36. return this;
  37. }
  38. normalize() {
  39. var len = this.length();
  40. if (len === 0) {
  41. this.x = 1;
  42. this.y = 0;
  43. } else {
  44. this.scale(1 / len);
  45. }
  46. return this;
  47. }
  48. rotate(rad) {
  49. let x = this.x;
  50. let y = this.y;
  51. this.x = x * Math.cos(rad) - y * Math.sin(rad);
  52. this.y = y * Math.cos(rad) + x * Math.sin(rad);
  53. return this;
  54. }
  55. }