Permalink
Browse files

vec2.cross

  • Loading branch information...
1 parent 30b4242 commit 3e385198e72459df9d11435f572baf56e44ce65a @sinisterchipmunk sinisterchipmunk committed May 3, 2012
Showing with 46 additions and 0 deletions.
  1. +29 −0 gl-matrix.js
  2. +17 −0 spec/javascripts/vec2_spec.js
View
@@ -2420,6 +2420,35 @@
return dest;
};
+ /**
+ * Computes the cross product of two vec2's. Note that the cross product must by definition
+ * produce a 3D vector. If a dest vector is given, it will contain the resultant 3D vector.
+ * Otherwise, a scalar number will be returned, representing the vector's Z coordinate, since
+ * its X and Y must always equal 0.
+ *
+ * Examples:
+ * vec2.cross([1, 2], [3, 4], vec3.create())
+ * //=> [0, 0, -2]
+ *
+ * vec2.cross([1, 2], [3, 4])
+ * //=> -2
+ *
+ * See http://stackoverflow.com/questions/243945/calculating-a-2d-vectors-cross-product
+ * for some interesting facts.
+ *
+ * @param {vec2} vecA left operand
+ * @param {vec2} vecB right operand
+ * @param {vec2} [dest] optional vec2 receiving result. If not specified a scalar is returned
+ *
+ */
+ vec2.cross = function (vecA, vecB, dest) {
+ var z = vecA[0] * vecB[1] - vecA[1] * vecB[0];
+ if (!dest) return z;
+ dest[0] = dest[1] = 0;
+ dest[2] = z;
+ return dest;
+ };
+
/*
* Exports
*/
@@ -13,6 +13,23 @@ describe("vec2", function() {
});
});
+ describe("cross", function() {
+ describe("with dest given", function() {
+ beforeEach(function() { result = vec2.cross(vecA, vecB, dest); });
+ it("should store the cross in dest", function() { expect(dest).toBeEqualish([0, 0, -2]); });
+ it("should return dest", function() { expect(result).toBe(dest); });
+ it("should not alter vecA", function() { expect(vecA).toBeEqualish([1, 2]); });
+ it("should not alter vecB", function() { expect(vecB).toBeEqualish([3, 4]); });
+ });
+
+ describe("with no dest given", function() {
+ beforeEach(function() { result = vec2.cross(vecA, vecB); });
+ it("should return the scalar Z value", function() { expect(result).toBeEqualish(-2); });
+ it("should not alter vecA", function() { expect(vecA).toBeEqualish([1, 2]); });
+ it("should not alter vecB", function() { expect(vecB).toBeEqualish([3, 4]); });
+ });
+ });
+
describe("normalize", function() {
describe("with dest given", function() {
beforeEach(function() { result = vec2.normalize(vecA, dest); });

0 comments on commit 3e38519

Please sign in to comment.