0

I have a the a dotProduct function an a magnitude function. I am struggling to combine these to get the radians between of two vectors.

What I have so far is:

 Vector.prototype.angleBetween = function (secondVector) {
    var Vec1, Vec2, Vec3, Dot;
    Vec1 = this.magnitude();
    Vec2 = secondVector.magnitude();
    Vec3 = Vec1.getX() * Vec2.getX() + Vec1.getY() * Vec2.getY();
    Dot = Vec3 / Vec1 * Vec2;
    return new Math.cos(Dot);
};

I know I need to do the Dotproduct of the two vectors / magnitude of vec1 * vec2.

It must pass this jasmine test:

describe("Angle between", function () {
    var secondVector, angleBetween;
    secondVector = new Vector(-40, 30, 0);
    angleBetween = secondVector.angleBetween(vector);

    it("Result is PI/2", function () {
        expect(angleBetween).toBeCloseTo(Math.PI / 2, 1);
    });
});

Where am I going wrong on this?

Working Function:

Vector.prototype.angleBetween = function (secondVector) {
    var Vec1, Vec2, Vec3, Dot;


    Vec1 = this.magnitude();
    Vec2 = secondVector.magnitude();

    Vec3 = this.getX() * this.getY() + secondVector.getX() * secondVector.getY();

    Dot = this.dotProduct(this) * this.dotProduct(secondVector);

    return Math.acos(Vec3 / Vec1 * Vec2 * Math.PI / 2, 1);
};
QFuullY
  • 17
  • 1
  • 5

2 Answers2

0

You should return Math.acos (Vec3/(Vec1*Vec2)) Acos because you want the angle and parens to group the product of magnitudes. I Do not think new is needed.

Jeremy Kahan
  • 3,796
  • 1
  • 10
  • 23
0
Vec1 = this.magnitude();
Vec2 = secondVector.magnitude();
Vec3 = Vec1.getX() * Vec2.getX() + Vec1.getY() * Vec2.getY();

isnt magnitude the lenght of the vector? you assign it to variables vec1 and vec2 and then call getX and getY as if they where Vectors.

Maybe you meant Dot = this.getX() * secondVector.getX() + this.getY() * secondVector.getY();

and then

return acos(Dot/(Vec1*Vec2))

btw here are the functions https://evanw.github.io/lightgl.js/docs/vector.html

J dev
  • 66
  • 1
  • 9