0

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

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

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

4

3 回答 3

2

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

float xDistance = cursorX - imageX;
float yDistance = cursorY - imageY;
double rotationAngle = Math.toDegrees(Math.atan2(yDistance, xDistance));
于 2013-04-21T17:29:24.847 回答
2

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

Java 的Math类指定了一个静态方法atan2,该方法充当 tan^-1 函数(也称为“反正切”,因此称为“atan”)并以弧度返回角度。(有一种方法atan需要一个参数。请参阅链接的 Javadoc。)

为了找到从“玩家”坐标到鼠标光标坐标的角度(我假设您提到的这个“玩家”具有 x 和 y 坐标),我们需要执行类似的操作这个:

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

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

于 2013-04-21T17:32:18.497 回答
0

虽然这是两年前问的......

如果您需要鼠标在窗口中不断更新鼠标位置,请参阅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;
}

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

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

与鼠标位置相关的图片

于 2015-11-25T05:38:00.280 回答