1
\$\begingroup\$

I am trying to get a Sprite in LibGDX to look at the player's mouse. Here's the code I have (mind you, I am using JRuby):

target = mouse_position.sub(spatial.position)
rotation = MathUtils.atan2(target.y, target.x)
spatial.rotation = rotation * MathUtils.radiansToDegrees

This is definitely doing something, but it's not completely correct. Here's a GIF of what it looks like in action:

Rotation gone wrong

Where am I going wrong?

\$\endgroup\$
  • 2
    \$\begingroup\$ Looks like your results are simply offset by 90 degrees - try adding that to the rotation? \$\endgroup\$ – congusbongus Feb 28 '14 at 6:21
  • 1
    \$\begingroup\$ Either do what @congusbongus said or simply rotate your sprite by 90 degrees in a photo editor... \$\endgroup\$ – Savlon Feb 28 '14 at 8:07
  • \$\begingroup\$ Also, the title is now incorrect. It's not rotating a perfect 90 degrees all the time. Sometimes it's less, sometimes it's more. \$\endgroup\$ – Evan Walsh Mar 21 '14 at 1:43
  • \$\begingroup\$ I guess the root of the problem is pretty much the same as here: gamedev.stackexchange.com/questions/22167/… \$\endgroup\$ – bummzack Mar 21 '14 at 7:49
2
\$\begingroup\$

Turns out my sprites weren't being drawn at the correct position, so their rotation was happening incorrectly. Let the lesson be Always Draw At Your Sprite's Origin Because Bad Things Will Happen If You Don't Know What You're Doing.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Add this to your Sprite creation:

spatial.rotate90(false);

This will rotate the sprite's texture 90 degrees. From the docs:

Rotates this sprite 90 degrees in-place by rotating the texture coordinates. This rotation is unaffected by setRotation(float) and rotate(float).

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ I appreciate this answer is quite succinct as it is, but maybe expand on it by using his code and providing a full code answer so that the answer itself can stand on its own. \$\endgroup\$ – Tom 'Blue' Piddock Mar 7 '14 at 9:54
  • 1
    \$\begingroup\$ @Blue I updated the answer \$\endgroup\$ – LeSam Mar 7 '14 at 11:21
  • \$\begingroup\$ Thanks for the suggestion! I tried that and it's certainly closer to what I want, but not quite there. Notice in this GIF how it will lag behind or jump ahead from the cursor position. It may be related to my use of the OrthographicCamera. I'm not sure. I'm a bit stumped. Thank you for your help, though! \$\endgroup\$ – Evan Walsh Mar 7 '14 at 18:04
  • \$\begingroup\$ In your seconds GIF I think the problem comes from your algorithm, not from the sprite rotation (with my changes) \$\endgroup\$ – LeSam Mar 7 '14 at 19:02

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.