1
\$\begingroup\$

This question already has an answer here:

I'm making a top down shooter with Three.js and Box2d. I'm displaying all of the graphics in 3d, but all of the physics are done in 2d, so it's sort of like super smash bros in a way.

Anyway, how can I make the player (a simple cube) rotate towards the mouse position? I've tried googling around, but I can't find much.

\$\endgroup\$

marked as duplicate by Anko, bummzack, Trevor Powell, MichaelHouse May 29 '14 at 16:50

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

0
\$\begingroup\$

First get the location of the mouse and the object. Then use Atan2 to get the angle between vectors. Use object as v1 in the method below and the mouse as v2. Then the float returned should be your new facing location for your object.

This is written in C#. Should be easy to convert.

    public static float AngleBetweenVectors(Vector2 v1, Vector2 v2)
        { return (float)Math.Atan2(v2.Y - v1.Y, v2.X - v1.X); }
\$\endgroup\$
  • \$\begingroup\$ I tried that, but it doesn't give the full range of rotation. It only spins a quarter of the way, and then starts spinning in the opposite direction. \$\endgroup\$ – user46400 May 27 '14 at 0:05
  • \$\begingroup\$ Are you displaying all of the values (mouse / object / angle to face / current facing angle after applying the new facing angle.) ? Make sure to check these to see if there is a problem in your code somewhere. \$\endgroup\$ – deathismyfriend May 27 '14 at 0:08
  • \$\begingroup\$ Also, I'm not sure how to translate the mouse position on the screen to coordinates in the game. \$\endgroup\$ – user46400 May 27 '14 at 0:08
  • \$\begingroup\$ That is most likely your problem in code then. If the mouse position is not correct then the resulting angle will be wrong. \$\endgroup\$ – deathismyfriend May 27 '14 at 0:09
  • \$\begingroup\$ OK, I found out that the mouse coords are wrong. How should I convert the mouse coordinates on the screen to coordinates in the game? \$\endgroup\$ – user46400 May 27 '14 at 0:21

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