Vector2.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. /**
  2. * @author mr.doob / http://mrdoob.com/
  3. * @author philogb / http://blog.thejit.org/
  4. * @author egraether / http://egraether.com/
  5. * @author zz85 / http://www.lab4games.net/zz85/blog
  6. */
  7. THREE.Vector2 = function ( x, y ) {
  8. this.x = x || 0;
  9. this.y = y || 0;
  10. };
  11. THREE.Vector2.prototype = {
  12. constructor: THREE.Vector2,
  13. set: function ( x, y ) {
  14. this.x = x;
  15. this.y = y;
  16. return this;
  17. },
  18. copy: function ( v ) {
  19. this.x = v.x;
  20. this.y = v.y;
  21. return this;
  22. },
  23. clone: function () {
  24. return new THREE.Vector2( this.x, this.y );
  25. },
  26. add: function ( v1, v2 ) {
  27. this.x = v1.x + v2.x;
  28. this.y = v1.y + v2.y;
  29. return this;
  30. },
  31. addSelf: function ( v ) {
  32. this.x += v.x;
  33. this.y += v.y;
  34. return this;
  35. },
  36. sub: function ( v1, v2 ) {
  37. this.x = v1.x - v2.x;
  38. this.y = v1.y - v2.y;
  39. return this;
  40. },
  41. subSelf: function ( v ) {
  42. this.x -= v.x;
  43. this.y -= v.y;
  44. return this;
  45. },
  46. multiplyScalar: function ( s ) {
  47. this.x *= s;
  48. this.y *= s;
  49. return this;
  50. },
  51. divideScalar: function ( s ) {
  52. if ( s ) {
  53. this.x /= s;
  54. this.y /= s;
  55. } else {
  56. this.set( 0, 0 );
  57. }
  58. return this;
  59. },
  60. negate: function() {
  61. return this.multiplyScalar( -1 );
  62. },
  63. dot: function ( v ) {
  64. return this.x * v.x + this.y * v.y;
  65. },
  66. lengthSq: function () {
  67. return this.x * this.x + this.y * this.y;
  68. },
  69. length: function () {
  70. return Math.sqrt( this.lengthSq() );
  71. },
  72. normalize: function () {
  73. return this.divideScalar( this.length() );
  74. },
  75. distanceTo: function ( v ) {
  76. return Math.sqrt( this.distanceToSquared( v ) );
  77. },
  78. distanceToSquared: function ( v ) {
  79. var dx = this.x - v.x, dy = this.y - v.y;
  80. return dx * dx + dy * dy;
  81. },
  82. setLength: function ( l ) {
  83. return this.normalize().multiplyScalar( l );
  84. },
  85. lerpSelf: function ( v, alpha ) {
  86. this.x += ( v.x - this.x ) * alpha;
  87. this.y += ( v.y - this.y ) * alpha;
  88. return this;
  89. },
  90. equals: function( v ) {
  91. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  92. },
  93. isZero: function () {
  94. return ( this.lengthSq() < 0.0001 /* almostZero */ );
  95. }
  96. };
粤ICP备19079148号