Skip to content

Commit

Permalink
Add static version of Vector.normalize()
Browse files Browse the repository at this point in the history
  • Loading branch information
weslord committed Jan 17, 2021
1 parent 18dbd51 commit 3d34b2e
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions src/math/p5.Vector.js
Original file line number Diff line number Diff line change
Expand Up @@ -1213,6 +1213,20 @@ p5.Vector.prototype.dist = function dist(v) {
* // [0.4454354, 0.8908708, 0.089087084]
* </code>
* </div>
*
* <div class="norender">
* <code>
* // Static method
* let v_initial = createVector(10, 20, 2);
* // v_initial has components [10.0, 20.0, 2.0]
* let v_normalized = p5.Vector.normalize(v_initial);
* print(v_normalized);
* // returns a new vector with components set to
* // [0.4454354, 0.8908708, 0.089087084]
* // v_initial remains unchanged
* </code>
* </div>
*
* <div>
* <code>
* function draw() {
Expand Down Expand Up @@ -2321,4 +2335,29 @@ p5.Vector.mag = function mag(vecT) {
return Math.sqrt(magSq);
};

/**
* Normalize the vector to length 1 (make it a unit vector).
*/
/**
* @method normalize
* @static
* @param {p5.Vector} v the vector to normalize
* @param {p5.Vector} [target] the vector to receive the result (Optional)
* @return {p5.Vector} v normalized to a length of 1
*/
p5.Vector.normalize = function normalize(v, target) {
if (arguments.length < 2) {
target = v.copy();
} else {
if (!(target instanceof p5.Vector)) {
p5._friendlyError(
'The target parameter should be of type p5.Vector',
'p5.Vector.normalize'
);
}
target.set(v);
}
return target.normalize();
};

export default p5.Vector;

0 comments on commit 3d34b2e

Please sign in to comment.