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?
问题:
回答1:
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);
回答2:
The aiming is done like this:
The direction from the tank to the mouse is like:
float deltaX = mouse.x - tank.x;
float deltaY = mouse.y - tank.y;
// The resulting direction
return (int) (360 + Math.toDegrees(Math.atan2(deltaY, deltaX))) % 360;
Just update the direction of the tank to the current mouse position e.g. in the mouseMoved
event.
Rotating the image:
Have a look at stack overflow or the java doc: "Graphics2D", "affine transform", "translation"
. Maybe your engine already provides some library functions.
Hope that helps.
回答3:
To build on the above answer..
Because the y-axis is decreasing try:
float deltaX = mouse.x - tank.x;
float deltaY = tank.y - mouse.y;