Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Added linear interpolation and middle point vector functions #1

Merged
merged 2 commits into from

2 participants

Rilke Petrosky Ulloa TJ Holowaychuk
Rilke Petrosky Ulloa

Here is a couple of useful functions. Used a lot in games.
They've been tested.
This component initiative is awesome by the way...

TJ Holowaychuk
Owner
tj commented

great! thank you

TJ Holowaychuk tj merged commit 771f00f into from
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
This page is out of date. Refresh to see the latest.
Showing with 52 additions and 1 deletion.
  1. +8 −0 Readme.md
  2. +26 −1 index.js
  3. +18 −0 test/vector.js
8 Readme.md
View
@@ -73,6 +73,14 @@ a.distance(b);
Return the distance between vectors.
+### Vector#interpolated(v:Vector, s:Number)
+
+ Return the linear interpolation between vectors given a step point.
+
+### Vector#middle(v:Vector)
+
+ Return the middle position between vectors.
+
### Vector#toString()
Return "(x, y)" string representation.
27 index.js
View
@@ -126,7 +126,7 @@ Vector.prototype.degrees = function(){
/**
* Return the distance between vectors.
*
- * @param {Vector} p
+ * @param {Vector} v
* @return {Number}
* @api public
*/
@@ -138,6 +138,31 @@ Vector.prototype.distance = function(v){
};
/**
+ * Return the linear interpolation between vectors given a step point.
+ *
+ * @param {Vector} v
+ * @param {Number} a
+ * @return {Vector}
+ * @api public
+ */
+
+Vector.prototype.interpolated = function(v, a){
+ return new Vector(this.x * (1 - a) + v.x * a, this.y * (1 - a) + v.y * a);
+};
+
+/**
+ * Return the middle position between vectors.
+ *
+ * @param {Vector} v
+ * @return {Vector}
+ * @api public
+ */
+
+Vector.prototype.middle = function(v){
+ return this.interpolated(v, .5);
+};
+
+/**
* Return "(x, y)" string representation.
*
* @return {String}
18 test/vector.js
View
@@ -96,6 +96,24 @@ describe('Vector(x, y)', function(){
})
})
+ describe('#interpolated(v, a)', function(){
+ it('should return linear interpolation between vectors', function(){
+ var a = Vector(10, 10);
+ var b = a.interpolated(Vector(20, 20), .3);
+ assert(13 == b.x && 13 == b.y);
+ b = a.interpolated(Vector(12, 18), .93);
+ assert('11.86' == b.x.toFixed(2) && '17.44' == b.y.toFixed(2));
+ })
+ })
+
+ describe('#middle(v)', function(){
+ it('should return the middle point between vectors', function(){
+ var a = Vector(10, 10);
+ var b = a.middle(Vector(20, 20));
+ assert(15 == b.x && 15 == b.y);
+ })
+ })
+
describe('#toString()', function(){
it('should return a string representation', function(){
var p = new Vector(15, 30);
Something went wrong with that request. Please try again.