Debug java function return point x distance along a line
public Point getPointOnSegment(double length, int x1, int y1, int x2, int y2) {
if(length==0) return new Point(x2, y2);
double angle = Math.atan((double)(y2-y1)/(double)(x2-x1));
return new Point((int)((length*Math.cos(angle))+x1), (int)((length*Math.sin(angle))+y1));
}
I have found this function that is supposed to return a point on a line that is x distance along said line. But for some reason it sometimes returns a point in the opposite direction that is is supposed to. It seems to happen if the angle of the line is greater than 180 degrees.
I have been开发者_如何学运维 looking at this for way over 5 hours now and I am afraid that I have stared myself blind to the issue. Can anyone see what the problem is, or suggest a better function to substitute it?
The issue is that you loose signs with your division. For example if both distances are negative the result will be positive as it would be for both beeing positive.
Try to calculate the angle using method atan2
:
angle = Math.atan2((double)(y2-y1), (double)(x2-x1));
This function respects the signs of your differences in all cases and returns an angle for the complete clock. It also handles the special case for x2-x1
being zero.
精彩评论