2

到目前为止,我有一个 java 应用程序,我在其中画了一个圆圈(播放器),然后在顶部(枪管)上画了一个绿色矩形。我有它,所以当玩家移动时,枪管会随之移动。我希望它找到鼠标指向的位置,然后相应地旋转枪管。有关我的意思的示例,请查看我找到的此视频http://www.youtube.com/watch?v=8W7WSkQq5SU看看当他移动鼠标时玩家图像有何反应?

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

我的进步

那么我该如何旋转它呢?顺便说一句,我不喜欢使用仿射变换或 Graphics2D 旋转。我希望有更好的方法。谢谢

4

2 回答 2

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无论如何都使用抗锯齿等是个好主意。

于 2012-08-11T03:36:54.327 回答
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();

    }
}

会产生这种效果

旋转

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

于 2012-08-11T02:45:11.520 回答