Rotate image to 'point' to mouse position

2019-04-12 19:40发布

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?

标签: java slick2d
3条回答
冷血范
2楼-- · 2019-04-12 20:23

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);
查看更多
爷的心禁止访问
3楼-- · 2019-04-12 20:25

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.

查看更多
Summer. ? 凉城
4楼-- · 2019-04-12 20:27

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;
查看更多
登录 后发表回答