简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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