Question

I am trying to have a character hold a gun, but I want the gun to move with the mouse. For example, if the mouse is up, the gun points up. If the mouse is to the left, the gun points to the left. I used the player position and the mouse position to construct a right triangle, then used inverse sine to find the angle of elevation. However, this only works for 90 degrees of movement. Any ideas of how else I could approach this so that I get a full 360 degrees of rotation?

Code for calculating the angle:

private double calcAngle()
{
    double mouseX,mouseY,subX,subY,playerToMouse,mouseToSub,angle;
    mouseX = Mouse.getX();
    mouseY = Mouse.getY();
    subX = mouseX;
    subY = y;
    playerToMouse = Math.sqrt(Math.pow(x-mouseX,2)+Math.pow(y-mouseY,2));
    mouseToSub = Math.sqrt(Math.pow(mouseX-subX,2)+Math.pow(mouseY-subY,2));
    angle = Math.toDegrees(Math.asin(mouseToSub/playerToMouse));
    return angle;
}

Current rotation (Pink represents player; Green represents gun; Yellow represents mouse):

Was it helpful?

Solution

You can use Math.atan2(mouseY-gunY, mouseX-gunX) which will return an angle between pi and -pi radians, or 180 and -180 degrees after you convert it to degrees. The problem with using asin is that 1/1 is equal to -1/-1 which makes it impossible for the function to tell them apart, and you want different results in each case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top