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

前端 未结 3 1800
忘掉有多难
忘掉有多难 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:27

    To find the angle from a coordinate (0,0) to another coordinate (x,y), we can use the trigonometric function tan^-1(y/x).

    Java's Math class specifies a static method atan2 which acts as a tan^-1 function (also known as "arctangent", hence "atan") and returns the angle in radians. (There is a method atan which takes one argument. See the linked Javadoc.)

    In order to find the angle in degrees from the coordinate of your "player" to the coordinate of the mouse cursor, (I'll assume this "player" you make mention of has x and y coordinates), we need to do something like this:

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

    It is also of note that an angle of zero radians would indicate that the mouse is directly to the right of the player. You mention that the "default player image" points upwards; if you mean that before rotation, your image faces upward for the player, it would be more conventional to geometry and the Java implementation of atan2 to have your player face right "by default".

提交回复
热议问题