Brandon Falconer Brandon Falconer - 1 year ago 100
Android Question

Libgdx Player rotation messing up

I'm trying to program a player that rotates towards the mouse and travels towards the mouse at a certain speed. I am using an orthographic camera, however as soon as I set the camera's position to equal the players position, the player rotation stops working and goes all over the place. I believe it might have something to do with the mouse coordinates using the screen and not the world x and y. I have tried unprojecting Gdx.inout.getY/X to no prevail. Any help is much appreciated.

I am using this code to follow player:

cam.position.x = player.getX();
cam.position.y = player.getY();

And this code for rotation:
float mouseX = Gdx.input.getX();
float mouseY = (480 - Gdx.input.getY());

float originX = getWidth() / 2 + position.x;
float originY = getHeight() / 2 + position.y;

double angle = Math.atan2(mouseY - originY, mouseX - originX) * (180/Math.PI) + 90;

if (angle < 0)
angle += 360;

rotation = (float) angle;

direction.x = mouseX - position.x;
direction.y = mouseY - position.y;

double hyp = Math.sqrt(direction.x * direction.x + direction.y * direction.y);
direction.x /= hyp;
direction.y /= hyp;

position.x += direction.x * 2;
position.y += direction.y * 2;

Answer Source

Have you tried projecting (or unprojecting) the points?

ViewPort viewPort = new ... // which ever ViewPort you're using

Vector2 worldPoint = new Vector2(x, y);
Vector2 projected = viewPort.project(worldPoint);


Vector2 screenPoint = new Vector2(x, y);
Vector2 unprojected = viewPort.unproject(screenPoint);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download