tobahhh
tobahhh

Reputation: 381

How do I get the endpoints of a line in Java knowing angle, midpoint, and length

I need to find the endpoints of a line knowing its midpoint, angle, and length. First, I tried this:

    public Point getEndpointA(Point midpoint, double angle, double length) {
        Point a = new Point(0, 0);
        a.x = midpoint.x + (int) length * Math.cos(angle);
        a.y = midpoint.y + (int) length * Math.sin(angle);
        return a;
    }
    public Point getEnpointB(Point midpoint, double angle, double length) {
        Point b = new Point(0, 0);
        b.x = midpoint.x + (int) length * Math.cos(-angle);
        b.y = midpoint.y + (int) length * Math.sin(-angle);
        return b;
    }

and then I called these functions to get the enpoints of the lines. However, this was inaccurate, and the points weren't placed quite where I hoped. Then, I tried experimenting with the distance formula, but that didn't work because I am only just starting Algebra I and I was having trouble getting rid of exponents and radical signs, which is not covered in Algebra I. (I looked up the functions sin and cos, and I understand what they mean now, so that's how I know about them) So, can somebody write a function that would return the endpoints of a line based of its midpoint, angle, and length, and explain to me how it works?

Upvotes: 0

Views: 767

Answers (1)

riversun
riversun

Reputation: 838

You want to specify the angle in degrees like followings?

        public Point getEndpointA(Point midpoint, double angleDegee, double length) {
                Point a = new Point(0, 0);

                // convert degrees=>radians
                final double angleRad = Math.toRadians(angleDegee);

                a.x = (int) (midpoint.x + (int) length * Math.cos(angleRad));
                a.y = (int) (midpoint.y + (int) length * Math.sin(angleRad));

                return a;
        }

        public Point getEndpointB(Point midpoint, double angleDeg, double length) {
                Point b = new Point(0, 0);

                final double angleRad = Math.toRadians(angleDeg + 180d);

                b.x = (int) (midpoint.x + (int) length * Math.cos(angleRad));
                b.y = (int) (midpoint.y + (int) length * Math.sin(angleRad));

                return b;
        }

Upvotes: 1

Related Questions