Search code examples
javaswingrotationpositiongraphics2d

How to rotate an image towards cursor location?


I'm trying to rotate an image towards cursor location (the spin supposed to be from the center of the image and spin across itself towards cursor location)

    public void rotateImg(Graphics g)
    {
        Graphics2D g2 = (Graphics2D)g.create();

        int cursorX = MouseInfo.getPointerInfo().getLocation().x - panel.getLocationOnScreen().x; // Mouse pos
        int cursorY = MouseInfo.getPointerInfo().getLocation().y - panel.getLocationOnScreen().y;
        Point center = new Point(x+size/2,y+size/2); //Image center (x,y are the player's coordinates)
        double dx = cursorX - center.getX();
        double dy =cursorY - center.getY();

        System.out.println(Math.toDegrees(Math.atan2(dx,dy)));

        g2.rotate(Math.toRadians(Math.atan2(dy,dx)),center.x,center.y);
        g2.drawImage(playerImage,x,y,size,size, null);
    }

this function is running inside a thread so it never stops and I checked to see if the cursor positions are updating (they are) and so is the angle but when I run it it barely spins and cant even make a 45 degrees rotation

Thanks ahead!


Solution

  • Tried this:

    public void rotateImg(Graphics g)
        {
            double degrees;
            Graphics2D g2 = (Graphics2D)g.create();
    
            Point center = new Point(x+size/2,y+size/2); //Image center (x,y are the player's coordinates)
            int cursorX = MouseInfo.getPointerInfo().getLocation().x - panel.getLocationOnScreen().x; // Mouse pos
            int cursorY = MouseInfo.getPointerInfo().getLocation().y - panel.getLocationOnScreen().y;
            double dx = cursorX - center.getX();
            double dy = cursorY - center.getY();
    
            degrees = Math.toDegrees(Math.atan2(dy,dx))+90;
    
            g2.rotate(Math.toRadians(degrees),center.x,center.y);
            g2.drawImage(playerImage,x,y,size,size, null);
        }
    

    it worked!