Rotate image to 'point' to mouse position

Greg Treleaven picture Greg Treleaven · May 5, 2012 · Viewed 8.5k times · Source

I have a gun image on top of a tank image. I want the gun to point towards the mouse position so the mouse can be used to aim. The original gun image will be pointing upwards. I'm using Slick2D and it's image class has a rotate function that takes an angle. How would I go about doing this?

Answer

Jake Greene picture Jake Greene · May 5, 2012

You can find the location of the user's mouse by asking an Input object. This is done by asking the GameContainer for the input.

Input userInput = gameContainer.getInput();
float mouseX = userInput.getMouseX();
float mouseY = userInput.getMouseY();

The locations of the mouse and the gun can be used to determine the angle the gun needs to face. We can imagine drawing a line between the gun and the mouse and finding the angle of this line. This angle is the angle the gun needs to face in order to 'point' towards the mouse.

Vector2f gunLocation = gun.getLocation();
float xDistance = mouseX - gunLocation.x;
float yDistance = mouseY - gunLocation.y;
double angleToTurn = Math.toDegrees(Math.atan2(yDistance, xDistance));
gunImage.setRotation((float)angleToTurn);