Search code examples
javavectorpolygonvertex

Find degree at intersection between vectors in convex polygon


It's a bit of a homework question but I've been derping around for a while and haven't been able to get a 100% accurate answer. Given a polygon, I have to find the internal angle of any random vertex within that polygon. What I have been doing is taking the vertex before that and the vertex after it and then calculating the angle of incidence (say I treat my vertex as B), I make the edges AB and BC, then find the magnitude of each, then divide the dot product of the two by the magnitude of each.

I'm still off, particularly in the instance where I have vectors (0,10), (0,0), (10,0). Obviously the interior angle on that middle vector is 90 degrees, but when I compute it using magnitude and dot product I get 45 degrees for some weird reason.

Here is my code

double dx21 = one.x - two.x;
        double dx31 = one.x - three.x;
        double dy21 = one.y - two.y;
        double dy31 = one.y - three.y;
        double m12 = Math.sqrt(dx21*dx21 + dy21*dy21);
        double m13 = Math.sqrt(dx31*dx31 + dy31*dy31);
        double theta = Math.acos((dx21*dx31 + dy21*dy31)/ (m12 * m13));
        System.out.println(theta);
        System.out.println(Math.toDegrees(theta));

Is there anything blindingly obvious that I've missed? I'm traversing the vertexes counter-clockwise, as that is how the set is organised.


Solution

  • Your code is using point 'one' as the centre point, and then calculates the angle between 'two' and 'three' from that. So, if you put , in the vertices (0,0), (0,10), (10,0), you would get an angle of 90. The actual calculation is fine and works, you just have your vertex order messed up.