I am working on a project in Java. I am trying to move the points p2
, p3
, p4
just outside the circumference of the circle in the opposite direction to the point p1. Below is the image, which describes the problem, I am trying to solve.
//given two points, calculates the angle
public static double calcAngle(Point2D.Double p1, Point2D.Double p2) {
double deltaX = p2.x - p1.x;
double deltaY = p2.y - p1.y;
return (Math.atan2(deltaY, deltaX) * 180 / Math.PI);
}
//calculates a point on a circle given the angle, center of the circle and the radius
public static Point2D.Double pointOnCircle(Point2D.Double point, double radius , double angle) {
double x = Math.abs(point.x + (radius * Math.cos(angle * Math.PI / 180F)));
double y = Math.abs(point.y + (radius * Math.sin(angle * Math.PI / 180F)));
return new Point2D.Double(x,y);
}
How do I calculate the angle in Java coordinate system and destination co-ordinates for each of the points p2
, p3
, p4
?
I am yet to try the code above and would like to know if my approach is right before proceeding, since it is a part of the bigger project. Thanks in advance!
Your general idea seems workable but overly complicated. There is no need to convert from x/y-vector to angle and then back. SImply scaling vectors will be enough.
Point2D p = p2; // likewise for p3, p4
double factor = radius / p.distance(p1);
p.setLocation(p1.getX() + (p.getX() - p1.getX())*factor,
p1.getY() + (p.getY() - p1.getY())*factor);
This takes the vector (p - p1)
, ie the vector pointing from p1
towards p
, scales it by factor
and adds it to the position of p1
. The factor
is chosen such that the new distance is equal to radius
.
All of this will fail if p1
and p
are the same, since in this case you'll have a division by zero. If this can be a problem for you, you might want to ensure that factor
is a finite number, eg using Double.isFinite(double)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.