Java 2d方向鼠标点旋转

时间:2012-08-11 02:09:57

标签: java rotation 2d image-rotation

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

以下是目前游戏的图片:

My Progress

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

2 个答案:

答案 0 :(得分:10)

使用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进行抗锯齿处理等。

答案 1 :(得分:2)

使用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();

    }
}

会产生这种效果

Rotating

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