6
\$\begingroup\$

So I've been looking around to try and figure out how I make my sprite face my mouse. So far the sprite moves to where my mouse is by some vector math.

Now I'd like it to rotate and face the mouse as it moves. From what I've found this calculation seems to be what keeps reappearing:

Sprite Rotation = Atan2(Direction Vectors Y Position, Direction Vectors X Position)

I express it like so:

sp.Rotation = (float)Math.Atan2(directionV.Y, directionV.X);

If I just go with the above, the sprite seems to jitter left and right ever so slightly but never rotate out of that position. Seeing as Atan2 returns the rotation in radians I found another piece of calculation to add to the above which turns it into degrees:

sp.Rotation = (float)Math.Atan2(directionV.Y, directionV.X) * 180 / PI;

Now the sprite rotates. Problem is that it spins uncontrollably the closer it comes to the mouse. One of the problems with the above calculation is that it assumes that +y goes up rather than down on the screen. As I recorded in these two videos, the first part is the slightly jittery movement (A lot more visible when not recording) and then with the added rotation:

Jittery Movement

So my questions are:

  1. How do I fix that weird Jittery movement when the sprite stands still? Some have suggested to make some kind of "snap" where I set the position of the sprite directly to the mouse position when it's really close. But no matter what I do the snapping is noticeable.
  2. How do I make the sprite stop spinning uncontrollably?
  3. Is it possible to simply define the front of the sprite and use that to make it "face" the right way?
\$\endgroup\$
  • 2
    \$\begingroup\$ You can implement a dead zone around the mouse. When the sprite is "close enough" to the mouse. Just make it stop. Further, make sure the point you're measuring from is the same place you're rotating at. If you're rotating about the center, make sure you're measuring distance to the mouse from the center of the sprite. Just my thoughts, not sure if they'll work. \$\endgroup\$ – MichaelHouse Jul 27 '13 at 13:58
  • \$\begingroup\$ @Byte56 I managed to make the sprite always face the mouse. Now there is just the issue of making it stop spassing out completely when it's close to the mouse. \$\endgroup\$ – OmniOwl Jul 27 '13 at 16:05
  • \$\begingroup\$ Can we see the code Where you make the object move towards the mouse? \$\endgroup\$ – Andrew Wilson Aug 2 '15 at 2:43
  • \$\begingroup\$ @AndrewWilson This question is 2 years old. \$\endgroup\$ – OmniOwl Aug 4 '15 at 13:33
0
\$\begingroup\$

Only change the rotation whenever your distance is above a certain delta. Also center your sprite, right now you're using the top-left corner of the sprite.

\$\endgroup\$

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.