Skip to content

Commit

Permalink
vec2.cross
Browse files Browse the repository at this point in the history
  • Loading branch information
sinisterchipmunk committed May 3, 2012
1 parent 30b4242 commit 3e38519
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
29 changes: 29 additions & 0 deletions gl-matrix.js
Expand Up @@ -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
*/
Expand Down
17 changes: 17 additions & 0 deletions spec/javascripts/vec2_spec.js
Expand Up @@ -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); });
Expand Down

0 comments on commit 3e38519

Please sign in to comment.