将图像旋转到“指向”鼠标位置

我在坦克图像上面有一张枪图像。 我希望枪指向鼠标位置,这样鼠标就可以用来瞄准。 原始枪图像将指向上方。 我正在使用Slick2D,它的图像类有一个旋转function,需要一个角度。 我该怎么做呢?

您可以通过询问Input对象来找到用户鼠标的位置。 这是通过向GameContainer询问输入来完成的。

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

鼠标和枪的位置可用于确定枪需要面对的角度。 我们可以想象在枪和鼠标之间画一条线并找到这条线的角度。 该角度是枪需要面对的角度,以便“指向”鼠标。

 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); 

瞄准是这样完成的:

从坦克到鼠标的方向如下:

 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; 

只需将坦克的方向更新到当前鼠标位置,例如在mouseMoved事件中。

旋转图像:

看看堆栈溢出或java doc: "Graphics2D", "affine transform", "translation" 。 也许您的引擎已经提供了一些库函数。

希望有所帮助。

建立在上面的答案..

因为y轴正在减小,请尝试:

 float deltaX = mouse.x - tank.x; float deltaY = tank.y - mouse.y;