正如您在影像上看到的,我有一個 p1 和 p2 物件,其坐標為 (x,y),我知道這些值,并且我知道所有這些圓形物件的半徑。
但是,我想計算新的位置 x,y ,這將是 p3 中心點。基本上,如您所見,它是 p2 位置 半徑。
我正在為基于 libgdx 的 java 游戲執行此操作。我將不勝感激任何數學或 Java 語言方向/示例。

uj5u.com熱心網友回復:
有關解釋,請參見代碼注釋。
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 = 130.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 };
}
}

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/476749.html
上一篇:為什么從子類呼叫時超類欄位不同?
