Java: rotating image so that it points at the mouse cursor

前端 未结 3 1881
忘掉有多难
忘掉有多难 2021-01-27 17:37

I want the player image to point towards the mouse cursor. I use this code to get the postion of the mouse cursor:

private int cursorX = MouseInfo.getPointerInfo         


        
3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-27 18:21

    Though this was asked two years ago...

    If you need the mouse to keep updating the mouse position in the window, see mouseMotionListener. The current you use to get the mouse position is relative to the whole screen. Just keep that in mind.

    Otherwise, here is a method I use,

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

    In words, you get the angle of each of the θs as shown in the picture below and check if x or y are 0 and make a special case for that.

    The origin is the middle of the picture and each of the points (marked with a hand-drawn cross) is where the mouse position is.

提交回复
热议问题