我想在JPanel中绘制一个矩形,它将翻译并旋转自身以模仿汽车的运动。我已经能够使矩形平移并旋转,但它围绕(0,0)的原点旋转。我非常高兴能够让矩形移动和旋转,因为我对Java GUI非常陌生,但我似乎无法得到如何让矩形围绕自身旋转,因为我对它进行了更多尝试,并且何时我初始化矩形并将其旋转45度,它的位置发生了变化,我将假设它是从旋转方法附加的变换矩阵。Java GUI旋转和矩形的翻译
我通过网站检查了如何解决这个问题,但是我只找到了如何旋转矩形,而不是如何旋转和移动像模拟汽车的运动。我会假设它是关于它的变换矩阵,但我只是在猜测。所以我的问题是,我将如何能够让矩形能够旋转和移动,而不是针对JPanel中的某个点。
下面是我想到了到目前为止的代码:
public class Draw extends JPanel implements ActionListener {
private int x = 100;
private int y = 100;
private double theta = Math.PI;
Rectangle rec = new Rectangle(x,y,25,25);
Timer timer = new Timer(25,this);
Draw(){
setBackground(Color.black);
timer.start();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.white);
rec.x = 100;
rec.y = 100;
g2d.rotate(theta);
g2d.draw(rec);
g2d.fill(rec);
}
public void actionPerformed(ActionEvent e) {
x = (int) (x + (Math.cos(theta))*1);
y = (int) (y + (Math.sin(theta))*1);
theta = theta - (5*Math.PI/180);
repaint();
}
翻译,使得该矩形为中心(0,0)。旋转。翻过来。 – ApproachingDarknessFish