Java 2d rotation in direction mouse point

后端 未结 2 1758
暖寄归人
暖寄归人 2020-11-28 14:12

So far I have a java app where I draw a circle(player) and then draw a green rectangle on top(gun barrel). I have it so when the player moves, the barrel follows with it. I

2条回答
  •  南笙
    南笙 (楼主)
    2020-11-28 14:29

    Using AffineTransform, sorry, only way I know how :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();
    
        }
    }
    

    Will produce this effect

    Rotating

    The red line (point out from the center) will want to follow the cursor.

提交回复
热议问题