如何将图像旋转到光标位置



我正试图将图像朝着光标位置旋转(旋转应该从图像的中心开始,并朝着光标的位置旋转(

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);
}

这个函数在线程中运行,所以它永远不会停止,我检查了光标位置是否在更新(它们是(,角度也在更新,但当我运行它时,它几乎不会旋转,甚至不能进行45度的旋转

谢谢!

尝试过这个:

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);
}

成功了!

最新更新