0

I want my player rotate towards mouse. Here's the code calculating the angle:

float angle = (float) Math.atan2(MouseInput.getMousePos().y - transform.position.y + transform.size.y / 2,
                MouseInput.getMousePos().x - transform.position.x + transform.size.x / 2);

        angle = (float) (angle * (180 / Math.PI));

        if (angle < 0) {

            angle = 360 + angle;
        }

        transform.rotation = 180 + angle;

And getMousePos() method (it just returns mouse pos relative to window):

public static Vector2 getMousePos() {

        Point p = MouseInfo.getPointerInfo().getLocation();
        return new Vector2(p.x - Game.w.getAccessToWindow(Acces.WINDOW_JFRAME_ACCES).getLocation().x,
                p.y - Game.w.getAccessToWindow(Acces.WINDOW_JFRAME_ACCES).getLocation().y);
}

Can you tell me what's wrong with this code? Player isn't rotating properly.

I tried following this article: https://gamefromscratch.com/gamedev-math-recipes-rotating-to-face-a-point/

Update: I found this post: Java 2d rotation in direction mouse point

Now I've updated my code to this:

int centerX = (int) (transform.size.x / 2);
        int centerY = (int) (transform.size.x / 2);
        int mouseX = (int) MouseInput.getMousePos().x;
        int mouseY = (int) MouseInput.getMousePos().y;
        double angle = Math.atan2(centerY - mouseY, centerX - mouseX) - Math.PI / 2;
        transform.rotation = angle;

But still something is off. Try this code for yourself. Maybe I did something wrong somewhere else.

boyernek
  • 45
  • 8
  • 2
    What happens instead? Did you step through your code with a debugger already? Do you also realize that `angle` first is expressed in radians and `angle = (float) (angle * (180 / Math.PI));` converts it to degrees? However, `transform.rotation` might need an angle in radians again - we can't tell because we don't know what `transform` is and how you're using it. – Thomas Mar 29 '21 at 12:23
  • Player sometimes isn't rotating towards mouse. Sometimes it is perfectly rotated and sometimes it off like 45 deg – boyernek Mar 29 '21 at 12:26
  • @Thomas also transform is just Vector2(float, float), Vector2(float, float), float. Example Transform transform = new Transform(new Vector2(0,0), new Vector2(20,20), 40f); – boyernek Mar 29 '21 at 12:27
  • Also I use java.awt.Graphics.rotate(rot, x, y). I think it uses radians as input. – boyernek Mar 29 '21 at 12:29
  • "I think it uses radians as input." - that's exactly the problem. If `rot` in that case is just `transformation.rotation` then you're passing the angle in degrees to a method that expects radians. You need to either stick to one form or make sure you always know what unit the angle is expressed in and convert accordingly. – Thomas Mar 29 '21 at 12:37

0 Answers0