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?
luckily for you I've done that not long ago :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public double computeAngle(Vector2f vec) { double distance = distance(0, 0, (int)vec.getX(), (int)vec.getY()); double angle = getAngle(vec, new Vector2f(0,-1)); if (vec.getX() < 0) angle *= -1; angle = Math.toDegrees(angle); }
public double getAngle(Vector2f vec1, Vector2f vec2) { double distanceV1 = distance(0, 0, (int)vec1.getX(), (int)vec1.getY()); double distanceV2 = distance(0, 0, (int)vec2.getX(), (int)vec2.getY()); double angle = Math.acos((vec1.getX() * vec2.getX() + vec1.getY() * vec2.getY()) / (distanceV1 * distanceV2)); return angle; }
public double distance(int x1, int y1, int x2, int y2) { return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) *(y2 - y1)); } |
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
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
Going to change that straight away >.<
edit2: should of used Vector2f.dot(vec1,vec2) instead of rewriting it myself too.