Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function Vector(x, y) {
- if (x === undefined)
- x = 0;
- if (y === undefined)
- y = 0;
- this.x = x;
- this.y = y;
- this.add = function(x, y) {
- if (y === undefined)
- y = x;
- this.x += x;
- this.y += y;
- return this;
- };
- this.addVector = function(other) {
- this.x += other.x;
- this.y += other.y;
- return this;
- };
- this.subtract = function(x, y) {
- if (y === undefined)
- y = x;
- this.x -= x;
- this.y -= y;
- return this;
- };
- this.subtractVector = function(other) {
- this.x -= other.x;
- this.y -= other.y;
- return this;
- };
- this.multiply = function(x, y) {
- if (y === undefined)
- y = x;
- this.x *= x;
- this.y *= y;
- return this;
- };
- this.multiplyVector = function(other) {
- this.x *= other.x;
- this.y *= other.y;
- return this;
- };
- this.divide = function(x, y) {
- if (y === undefined)
- y = x;
- this.x /= x;
- this.y /= y;
- return this;
- };
- this.divideVector = function(other) {
- this.x /= other.x;
- this.y /= other.y;
- return this;
- };
- this.magnitude = function() {
- return Math.sqrt(this.x * this.x + this.y * this.y);
- };
- this.direction = function() {
- return Math.atan(this.y / this.x);
- };
- this.distance = function(other) {
- return Math.sqrt(Math.pow(this.x - other.x, 2) + Math.pow(this.y - other.y, 2));
- };
- this.crossProduct = function(other) {
- return this.x * other.y - this.y * other.x;
- };
- this.normalize = function() {
- if (this.x == 0 && this.y == 0) {}
- else if (this.x == 0)
- this.divide(1, this.magnitude());
- else if (this.y == 0)
- this.divide(this.magnitude(), 1);
- else
- this.divide(this.magnitude());
- return this;
- };
- this.toString = function() {
- return this.x + "," + this.y;
- };
- this.clone = function() {
- return new Vector(this.x, this.y);
- };
- this.equals = function(other) {
- return other.x == this.x && other.y == this.y;
- };
- }
Advertisement
Add Comment
Please, Sign In to add comment