Rotate image to 'point' to mouse position

旧城冷巷雨未停 提交于 2019-12-06 12:13:13

问题


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;


来源:https://stackoverflow.com/questions/10461993/rotate-image-to-point-to-mouse-position

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!