import java.awt.*;
import javax.swing.*;
public class Window {
private int x;
private int y;
private int R = 30;
private double alpha = 0;
private final int SPEED = 1;
private final Color COLOR = Color.red;
public static void main(String[] args) {
new Window().buildWindow();
}
public void buildWindow() {
JFrame frame = new JFrame("Rotation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800,600);
frame.setVisible(true);
frame.add(new DrawPanel());
while(true) {
try {
Thread.sleep(60);
alpha += SPEED;
frame.repaint();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@SuppressWarnings("serial")
class DrawPanel extends JPanel {
@Override
public void paintComponent(Graphics g) {
g.setColor(Color.blue);
Font font = new Font("Arial",Font.PLAIN,12);
g.setFont(font);
g.drawString(String.format("Angle: %.2f ", alpha), 0, 12);
g.setColor(Color.black);
g.drawLine(this.getWidth()/2,0, this.getWidth()/2, this.getHeight());
g.drawLine(0, this.getHeight()/2, this.getWidth(), this.getHeight()/2);
x = (int) ((this.getWidth() / 2 - R / 2 ) + Math.round((R + 20) * Math.sin(alpha)));
y = (int) ((this.getHeight() / 2 - R / 2 ) + Math.round((R + 20) * Math.cos(alpha)));
g.setColor(COLOR);
g.fillOval(x, y, R, R);
}
}
}
这段代码看起来很有效,但后来我在屏幕上打印了Angle [alpha]信息。当我注释掉alpha+=SPEED
并手动输入角度时,它看起来不像是在工作。屏幕上的角度剂量与该角度alpha
不对应。
所以我需要建议。我应该改变什么?我的三角学错了吗?等...
答案 0 :(得分:2)
这里要注意三件事:
alpha
变量是度数,因为您在每个步骤中添加了20。但是,Math.sin()
和Math.cos()
方法需要一个以弧度为单位的角度。sin
和cos
来电。y
等式中的符号,以说明y
坐标从屏幕顶部开始向下增加通过这些修改,您的代码将按预期运行:
double rads = (alpha * Math.PI) / 180F;
x = (int) ((this.getWidth() / 2 - R / 2 ) + Math.round((R + 20) * Math.cos(rads)));
y = (int) ((this.getHeight() / 2 - R / 2 ) - Math.round((R + 20) * Math.sin(rads)));