Skip to content

Instantly share code, notes, and snippets.

@asarode
Last active August 29, 2015 14:25
Show Gist options
  • Select an option

  • Save asarode/120f0f923ab31ad8e730 to your computer and use it in GitHub Desktop.

Select an option

Save asarode/120f0f923ab31ad8e730 to your computer and use it in GitHub Desktop.

Revisions

  1. asarode revised this gist Jul 21, 2015. No changes.
  2. asarode created this gist Jul 21, 2015.
    43 changes: 43 additions & 0 deletions vectorious-origin.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    /*
    * Initial steps of the mateogianolio/vectorious library
    * https://github.com/mateogianolio/gravity/blob/master/js/vector.js
    */

    function Vector(x, y) {
    this.x = x;
    this.y = y;
    }

    // Addition
    Vector.prototype.add = function(vector) {
    return new Vector(this.x + vector.x, this.y + vector.y);
    };

    // Subtraction
    Vector.prototype.subtract = function(vector) {
    return new Vector(this.x - vector.x, this.y - vector.y);
    };

    // Dot product
    Vector.prototype.dot = function(vector) {
    return (this.x * vector.x + this.y * vector.y);
    }

    // Scaling
    Vector.prototype.scale = function(c) {
    return new Vector(this.x * c, this.y * c);
    }

    // Calculation of magnitude
    Vector.prototype.magnitude = function() {
    return Math.sqrt(this.x * this.x + this.y * this.y);
    }

    // Calculation of unit vector
    Vector.prototype.unitvector = function() {
    var mag = this.magnitude();
    if(mag != 0)
    return new Vector(this.x / mag, this.y / mag);

    return new Vector(0, 0);
    }