1
\$\begingroup\$

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\$
0

1 Answer 1

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\$
6
  • \$\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\$ Commented May 27, 2014 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\$ Commented May 27, 2014 at 0:08
  • \$\begingroup\$ Also, I'm not sure how to translate the mouse position on the screen to coordinates in the game. \$\endgroup\$ Commented May 27, 2014 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\$ Commented May 27, 2014 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\$ Commented May 27, 2014 at 0:21

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.