In my 2D game, I have a simple player sprite that moves with WASD. I want to make it rotate to follow my mouse, so the front of the sprite always points at the mouse. I know this is probably some advanced math, can anyone help?
Edit: Here is the final code we came up with:
// centerX and centerY are the center points of the sprite. playerX and playerY are the co-ordinates of the sprite.
float centerX = playerX + player.getWidth() / 2;
float centerY = playerY + player.getHeight() / 2;
float radiansToMouse = (float) Math.atan2(centerX - input.getMouseX(), centerY - input.getMouseY());
float degreesToMouse = (57.2957795f * radiansToMouse) * -1;
player.setRotation(degreesToMouse);
Might be more efficient ways, or cleaner code. But this is what I managed to get after some thinking around and putting together math formulas. Vector2f is from le lwjgl package, but you can replace it with whatever implementation of a vector you want.
And this code works assuming that the player’s sprite is directed to the top of the image. If it’s not the case, change
new Vector2f(0,-1)
with the director vector of your sprite.
Btw, if others have tips to improve the efficiency / cleanliness of this code, I’d be grateful !
edit : Should of done this way before, but instead of using the function distance I put up there, I should of used
vec.length();
Going to change that straight away >.<
edit2: should of used Vector2f.dot(vec1,vec2) instead of rewriting it myself too.
that angle is the angle you have to set your image’s rotation to.
all images should fact LEFT at 0 degrees, in file format… so your png or whatever should face left.
FastMath is just a faster Math Lib provided by Riven amoung others.
You can use any atan2 method; one is provided by the default Math class
Remember that if you have a camera / offset / more than one screen size, you have to offset the mouse/sprite location for the calculation
Yeah, actually I just checked, and “angle between two points” returns me the atan2 function in the first hit. The problem is (because I was working with vectors) I typed “angle between two vectors” which game me the formula with the dot product and stuff. Funny how things can change because you’re satisfied with the one result and don’t think there is anything simpler