简体   繁体   English

需要帮助以自上而下的射击游戏(Java)使图像旋转以面对鼠标

[英]Need help getting image to rotate to face the mouse in a top-down shooter (Java)

I am having trouble with the movement of the player in my game. 我在游戏中遇到玩家移动的麻烦。 The game is a top-down shooter in which the location of the player is controlled with W, A, S, and D. I want to control the direction the player faces by moving the mouse. 该游戏是自上而下的射击游戏,其中,玩家的位置由W,A,S和D控制。我想通过移动鼠标来控制玩家面对的方向。

I know I need to use the mouseMoved method to track the mouse, but I am lost in both calculating the angle and actually rotating the image. 我知道我需要使用mouseMoved方法来跟踪鼠标,但是我在计算角度和实际旋转图像时都迷失了方向。

The image is basically a circle with black line to represent the gun sticking out. 该图像基本上是带有黑线的圆圈,表示喷枪伸出。

Any help is greatly appreciated! 任何帮助是极大的赞赏!

You can calculate the angle using the player and mouse coordinates: 您可以使用播放器和鼠标坐标来计算角度:

float angle = (float)(Math.atan2(player.y - mouse.y, player.x - mouse.x));

this will give you the angle in radians. 这将为您提供以弧度为单位的角度。

Then when you are drawing the object: 然后在绘制对象时:

AffineTransform reset = new AffineTransform();
reset.rotate(0, 0, 0);
Graphics2D g2 = (Graphics2D)g;
g2.rotate(angle, player.x, player.y);
//draw the image here
g2.setTransform(reset);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM