Issue
As you can see on the image, I have a p1 and p2 objects with (x,y) coordinates which I know the values, and I know radius of all these circle objects.
However, I want to calculate new position x,y which would be p3 center point. Basically, as you can see it's p2 position + radius.
I am doing this for java game which is based on libgdx. I would appreciate any math or java language directions/examples.
Solution
See code comments for explanation.
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import javax.swing.*;
class CenteredCircle extends Ellipse2D.Double {
CenteredCircle(double x, double y, double radius) {
super(x - radius, y - radius, 2 * radius, 2 * radius);
}
}
public class CircleDemo extends JFrame {
public CircleDemo() {
int width = 640; int height = 480;
setSize(new Dimension(width, height));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
JPanel p = new JPanel() {
@Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
double radius = 50.0;
double[] p1 = { width/2, height/2 };
// big circle
Shape circle2 = new CenteredCircle(p1[0], p1[1], radius);
g2d.draw(circle2);
// 12 small circles
for (int angle = 0; angle < 360; angle += 30) {
// this is the magic part
// a polar co-ordinate has a length and an angle
// by changing the angle we rotate
// the transformed co-ordinate is the center of the small circle
double[] coord = polarToCartesian(radius, angle);
// draw line just for visualization
Line2D line = new Line2D.Double(p1[0], p1[1], p1[0] + coord[0], p1[1] + coord[1]);
g2d.draw(line);
// draw the small circle
Shape circle = new CenteredCircle(p1[0] + coord[0], p1[1] + coord[1], radius/4);
g2d.draw(circle);
}
}
};
setTitle("Circle Demo");
this.getContentPane().add(p);
}
public static void main(String arg[]) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new CircleDemo();
}
});
}
static double[] polarToCartesian(double r, double theta) {
theta = (theta * Math.PI) / 180.0; // multiply first, then divide to keep error small
return new double[]{ r * Math.cos(theta), r * Math.sin(theta) };
}
// not needed, just for completeness
public static double[] cartesianToPolar(double x, double y) {
return new double[]{ Math.sqrt(x * x + y * y), (Math.atan2(y, x) * 180) / Math.PI };
}
}
Answered By - Franck
Answer Checked By - Marilyn (JavaFixing Volunteer)