Search code examples
javascriptmathvector3dangle

Calculating angle between 3 points give weird result according pattern angle


I want to calculate the angle between two segments in 2D space. The two segments are defined by AB and BC.

The result of the calculation seems to vary according to the orientation of the vectors.

function getAngle2D(A, B, C) {
        
        const A2D = { x: A.x, y: A.y };
        const B2D = { x: B.x, y: B.y };
        const C2D = { x: C.x, y: C.y };

        // Vecteurs AB et BC
        const AB = { x: B2D.x - A2D.x, y: B2D.y - A2D.y };
        const BC = { x: C2D.x - B2D.x, y: C2D.y - B2D.y };

        // Produit scalaire des vecteurs AB et BC
        const dotProduct = AB.x * BC.x + AB.y * BC.y;

        // Normes des vecteurs AB et BC
        const magnitudeAB = Math.sqrt(AB.x ** 2 + AB.y ** 2);
        const magnitudeBC = Math.sqrt(BC.x ** 2 + BC.y ** 2);

        // Calculer le cosinus de l'angle
        const cosTheta = dotProduct / (magnitudeAB * magnitudeBC);

        // Calculer l'angle en radians
        const angleRadians = Math.acos(cosTheta);

        // Convertir l'angle en degrés
        const angleDegrees = angleRadians * (180 / Math.PI);

        return angleDegrees;
    }



        // first points batch (green)
        const points1 = [
            {x: 0.5067973136901855, y: 0.5480734705924988,},
            { x: 0.5307877659797668, y: 0.5041729211807251},
            { x: 0.5793206095695496, y: 0.5759181380271912}
        ];

        // second points batch (blue)
        const points2 = [
            {  x: 0.3797118365764618, y: 0.7955537438392639,  },
            {  x: 0.3800569176673889, y: 0.7407315969467163,  },
            {x: 0.4513204097747803, y: 0.7465168237686157, }
        ];

enter image description here

(don't pay attention to projection lines)


Solution

  • I believe your maths is correct, and these 2 vectors are not at 90 degrees.

    Were they at 90 degrees, their dot product would be zero;

    Instead, the dot product of AB (-1,-1,-1) and BC (-1,1,-1) is 1.0.

    Each vector has a magnitude of sqrt{3}.

    Therefore cos(\theta) = 1/ sqrt{3}/ sqrt{3} = 1/3

    \theta ~= 70.52 deg

    Note that the angle between (-1,-1,0) and (-1,1,0) is 90 degrees. Then we add an equal Z component to both, lessening the angle.

    On a side note, you're currently calculating this angle, you should check that is actually what you intend;

    enter image description here