Java 2d方向鼠标点旋转

到目前为止,我有一个java应用程序,我绘制一个圆圈(播放器),然后在顶部(枪管)绘制一个绿色矩形。 我有它,所以当玩家移动时,枪管随之而来。 我想让它找到鼠标指向的位置,然后相应地旋转桶。 我的意思是看看这个video的一个例子我发现http://www.youtube.com/watch?v=8W7WSkQq5SU看看玩家图像在移动鼠标时的反应如何?

这是目前为止游戏的样子:

我的进步

那我怎么像这样旋转呢? 顺便说一句我不喜欢使用affinetransform或Graphics2D旋转。 我希望有更好的方法。 谢谢

使用Graphics2D旋转方法确实是最简单的方法。 这是一个简单的实现:

 int centerX = width / 2; int centerY = height / 2; double angle = Math.atan2(centerY - mouseY, centerX - mouseX) - Math.PI / 2; ((Graphics2D)g).rotate(angle, centerX, centerY); g.fillRect(...); // draw your rectangle 

如果要在完成后移除旋转,可以继续正常绘制,请使用:

 Graphics2D g2d = (Graphics2D)g; AffineTransform transform = g2d.getTransform(); g2d.rotate(angle, centerX, centerY); g2d.fillRect(...); // draw your rectangle g2d.setTransform(transform); 

最好只使用Graphics2D进行抗锯齿等。

使用AffineTransform ,对不起,只有我知道如何:P

 public class RotatePane extends javax.swing.JPanel { private BufferedImage img; private Point mousePoint; /** * Creates new form RotatePane */ public RotatePane() { try { img = ImageIO.read(getClass().getResource("/MT02.png")); } catch (IOException ex) { ex.printStackTrace(); } addMouseMotionListener(new MouseAdapter() { @Override public void mouseMoved(MouseEvent e) { mousePoint = e.getPoint(); repaint(); } }); } @Override public Dimension getPreferredSize() { return new Dimension(img.getWidth(), img.getHeight()); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g.create(); double rotation = 0f; int width = getWidth() - 1; int height = getHeight() - 1; if (mousePoint != null) { int x = width / 2; int y = height / 2; int deltaX = mousePoint.x - x; int deltaY = mousePoint.y - y; rotation = -Math.atan2(deltaX, deltaY); rotation = Math.toDegrees(rotation) + 180; } int x = (width - img.getWidth()) / 2; int y = (height - img.getHeight()) / 2; g2d.rotate(Math.toRadians(rotation), width / 2, height / 2); g2d.drawImage(img, x, y, this); x = width / 2; y = height / 2; g2d.setStroke(new BasicStroke(3)); g2d.setColor(Color.RED); g2d.drawLine(x, y, x, y - height / 4); g2d.dispose(); } } 

会产生这种效果

旋转

红线(从中心指出)将要跟随光标。