gpt4 book ai didi

Java AWT旋转球

转载 作者:行者123 更新时间:2023-11-30 04:08:08 25 4
gpt4 key购买 nike

天哪,三角学太难了!我有点需要一些帮助,这是一个简单的程序,应该围绕屏幕中心旋转球...这是我的代码:

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);
}
}
}

这段代码看起来很有效,但随后我已将角度[alpha]信息打印到屏幕上。当我注释掉 alpha+=SPEED 并手动输入角度时,它看起来不起作用。屏幕上的角度与该角度 alpha 不对应。所以我需要建议。我应该改变什么?我的三角函数有错吗?等等...

最佳答案

这里需要注意三件事:

  1. 我假设您的 alpha 变量以度为单位,因为您在每一步中都添加了 20。但是,Math.sin()Math.cos() 方法需要以弧度为单位的角度。
  2. 通常 0 度(或 0 弧度)表示在“3 点钟”位置。为此,您需要切换 sincos 调用。
  3. 反转 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)));

关于Java AWT旋转球,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20267546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com