Search code examples
unity-game-enginemathvectorvirtual-realityangle

Unity3d: Angle between two points not consistent


So, I have two game objects P1 and P2, these two game objects are associated with the trackers on my left leg and right leg respectively.

So, I need to find the angle between them.

enter image description here

So, this is how my P1 and P2 would look if I face forward and take my right leg front.

private double calculateAngle(double P1X, double P1Y, double P2X, double P2Y,
        double P3X, double P3Y)
{

    double numerator = P2Y * (P1X - P3X) + P1Y * (P3X - P2X) + P3Y * (P2X - P1X);
    double denominator = (P2X - P1X) * (P1X - P3X) + (P2Y - P1Y) * (P1Y - P3Y);
    double ratio = numerator / denominator;

    double angleRad = Math.Atan(ratio);
    double angleDeg = (angleRad * 180) / Math.PI;

    if (angleDeg < 0)
    {
        angleDeg = 180 + angleDeg;
    }

    return angleDeg;
}

    calculateAngle(LeftLegController.position.x, LeftLegController.position.z,
              RightLegController.position.x, RightLegController.position.z, 
        LeftLegController.position.x, RightLegController.position.z))

It should always be a right angle triangle due to this.

So, this is the code I'm using to calculate the angle between my P1 and P2,

When I face front, the angle between my two game objects is different and when I face left and move my right leg front (Which would look like this)

enter image description here

My Angle 1 and Angle 2 are coming entirely different. So, what is a better way to find an angle (Ignoring the y axis, its as if the points are projected on the ground)


Solution

  • I believe the method you're looking for is Vector3.SignedAngle().

    var A = Vector3.ProjectOnPlane(P3.position - P1.position, Vector3.up);
    var B = Vector3.ProjectOnPlane(P2.position - P1.position, Vector3.up);
    print(Vector3.SignedAngle(A, B, Vector3.up));