WIllJBD
WIllJBD

Reputation: 6154

Java innacurate in calulating my angle?

I am having a user draw a line on the screen, there is a start point and a end point. If the user extends over a certain angle I change the position of the endpoint so the user cannot extend beyond the specified angle. However it seems that when I cacluate the angle the user is drawing and make suer it is not over MAX ANGLE, and set the angle to the MAX ANGLE, there is a difference. This can be seen by when I draw the line, once i get to a certain angle, the line jumps and locks at the MAX ANGLE, but there shouldnt be any jump, it should be smooth, like the line ran into a invisible barrier. This could just be me though, my PosX and PosY are floats.

    private void CheckAngle() {
    double adj = Math.abs(PosX - PosX2);
    double c1 = adj;
    double c2 = Math.abs(PosY - PosY2);
    double hyp = Math.hypot(c1, c2);


    double angle = Math.cos((adj/hyp));
    angle = angle * 100;


    if (angle > MAX_ANGLE) {


        double opp = (Math.tan(MAX_ANGLE) * Math.abs(PosX - PosX2));


        if (PosY > PosY2) {
            PosY2 =(float) (PosY - opp);
        } else {
            PosY2 =(float) (PosY + opp);
        }

    }
}

My answer was a combination of using radians, as well as unsing

    Math.acos() & Math.atan()

so the final code looks like this

    private void CheckAngle() {
    double adj = Math.abs(PosX - PosX2);
    double opp = Math.abs(PosY - PosY2);
    double hyp = Math.sqrt((adj*adj)+(opp*opp));


    double angle = Math.acos((adj/hyp));
    angle = angle * 100;
    angle = Math.toRadians(angle);

    if (angle > MAX_ANGLE) {


        opp = (Math.atan(MAX_ANGLE) * adj);


        if (PosY > PosY2) {
            PosY2 =(float) (PosY - opp);
        } else {
            PosY2 =(float) (PosY + opp);
        }

    }
}

Upvotes: 0

Views: 126

Answers (1)

jrad
jrad

Reputation: 3190

Here's the conversion:

final double MAX_ANGLE = Math.toRadians(80);

Note that this is identical to saying:

final double MAX_ANGLE = 80 * Math.PI / 180;

Upvotes: 2

Related Questions