Java:旋转图像使其指向鼠标光标

我希望播放器图像指向鼠标光标。 我用这段代码来获取鼠标光标的位置:

private int cursorX = MouseInfo.getPointerInfo().getLocation().x; private int cursorY = MouseInfo.getPointerInfo().getLocation().y; 

注意:默认播放器图像指向上方

您必须使用三角法来计算旋转角度。 为此,您首先需要获取图像和光标的位置。 我无法告诉你如何获得图像的位置,因为这可能会有所不同。 对于这个例子(从这里改编),我假设imageXimageY是图像的xy位置:

 float xDistance = cursorX - imageX; float yDistance = cursorY - imageY; double rotationAngle = Math.toDegrees(Math.atan2(yDistance, xDistance)); 

为了找到从坐标(0,0)到另一个坐标(x,y)的角度,我们可以使用三角函数tan ^ -1(y / x)。

Java的Math类指定一个静态方法atan2 ,它充当tan ^ -1函数(也称为“arctangent”,因此是“atan”)并以弧度为单位返回角度。 (有一个方法atan ,它接受一个参数。请参阅链接的Javadoc。)

为了找到从“玩家”坐标到鼠标光标坐标的角度,(我假设这个“玩家”你提到有x和y坐标),我们需要做类似的事情这个:

 double theta = Math.atan2(cursorY - player.getY(), cursorX - player.getX()); 

还需要注意的是,零弧度的角度表示鼠标直接位于播放器的右侧 。 你提到“默认玩家形象”指向上方; 如果你的意思是在旋转之前,你的图像朝向玩家,那么几何图形和atan2的Java实现更常规,让你的玩家面对“默认”。

虽然这是两年前问的……

如果需要鼠标在窗口中更新鼠标位置,请参阅mouseMotionListener 。 用于获取鼠标位置的当前电流是相对于整个屏幕的。 要时刻铭记在心。

否则,这是我使用的方法,

 public double angleInRelation(int x1, int y1, int x2, int y2) { // Point 1 in relation to point 2 Point point1 = new Point(x1, y1); Point point2 = new Point(x2, y2); int xdiff = Math.abs(point2.x - point1.x); int ydiff = Math.abs(point2.y - point1.y); double deg = 361; if ( (point2.x > point1.x) && (point2.y < point1.y) ) { // Quadrant 1 deg = -Math.toDegrees(Math.atan(Math.toRadians(ydiff) / Math.toRadians(xdiff))); } else if ( (point2.x > point1.x) && (point2.y > point1.y) ) { // Quadrant 2 deg = Math.toDegrees(Math.atan(Math.toRadians(ydiff) / Math.toRadians(xdiff))); } else if ( (point2.x < point1.x) && (point2.y > point1.y) ) { // Quadrant 3 deg = 90 + Math.toDegrees(Math.atan(Math.toRadians(xdiff) / Math.toRadians(ydiff))); } else if ( (point2.x < point1.x) && (point2.y < point1.y) ) { // Quadrant 4 deg = 180 + Math.toDegrees(Math.atan(Math.toRadians(ydiff) / Math.toRadians(xdiff))); } else if ((point2.x == point1.x) && (point2.y < point1.y)){ deg = -90; } else if ((point2.x == point1.x) && (point2.y > point1.y)) { deg = 90; } else if ((point2.y == point1.y) && (point2.x > point1.x)) { deg = 0; } else if ((point2.y == point2.y) && (point2.x < point1.x)) { deg = 180; } if (deg == 361) { deg = 0; } return deg; } 

换句话说,你得到每个θ的角度,如下图所示,检查x或y是否为0,并为此做出特殊情况。

原点是图片的中间,每个点(用手绘十字标记)是鼠标位置的位置。

与鼠标位置有关的图片