Game
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 1.0KB

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