0
\$\begingroup\$

I am tryna makin' a 2D game with a 3D player (kinda of Factorium). I got stuck on the rotating of the player. I'd like it look always torwards to the mouse. e.g. If I move mouse on the top-left of the window, player will rotate towards the same direction.

I read on some other question about the method below, but it doesn't work properly:

private void rotatePlayerToMouse(OrthographicCamera camera) {

    Vector3 mousePos = camera.unproject(new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0));
    Vector3 playerPos = this.getPosition();//this.instance.transform.getTranslation(Vector3)

    float degree = (float)Math.atan2(mousePos.y - playerPos.y, mousePos.x - playerPos.x);
    System.out.println(degree);
    this.instance.transform.rotate(new Vector3(0f, 0f, 1f), degree);
}

This method allows player to rotate. Player rotates both direction, but it doesn't stop rotating...

What is wrong?

\$\endgroup\$
1
\$\begingroup\$

Two obvious problems here:

  • You've labelled a variable degree that's actually measured in radians, not in degrees.

  • You're telling the object how much to rotate by, not giving it a target angle it should rotate to.

These can both be solved by reading the documentation for the methods you're using. It tends to show when you don't. 😉

float radians = (float)Math.atan2(mousePos.y - playerPos.y, mousePos.x - playerPos.x);

this.instance.transform.setFromEulerAnglesRad(0, 0, radians).setTranslation(playerPos);
\$\endgroup\$
4
  • \$\begingroup\$ setToLookAt would be even better due to matching intent and fewer calculations. \$\endgroup\$ – Shadows In Rain Mar 20 at 19:21
  • \$\begingroup\$ I was concerned that setToLookAt might point the object's z+ axis at the target (as the corresponding method does in Unity), rather than the x+ axis as it looks like OP is trying to do here. I'd welcome a second answer if I got this wrong though! \$\endgroup\$ – DMGregory Mar 20 at 19:28
  • \$\begingroup\$ Sure it is working...almost properly: I scaled my model with 32f, 32,f -32f. And when I move mouse, scale has been reset. But doesn't mind. I will scale with BlockBench and not more in runtime. . Anyway this.instance.setFromEulerAnglesRad is instead this.instance.transform.setFromEulerAnglesRad. I just had to sub PI/2 to adjust axis. Really thanks for your help \$\endgroup\$ – DynoZ Mar 20 at 20:21
  • \$\begingroup\$ I was concerned that setToLookAt might point the object's z+ axis at the target in fact I had some similar problem when I tried using it \$\endgroup\$ – DynoZ Mar 20 at 20:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.