- Home /

# Joystick to turn object

I have an onscreen joystick that spits out a Vector2 for horizontal and vertical movement. The range is -1.0 to 1.0 What I need to do is based on that vector, calculate the rotation of an object to face the direction of the joystick and also to move at a rate based on how far the joystick is moved in that direction. An example would be if the joystick is half the way down and half way to the right, the horizontal value would be 0.5 and vertical would be -0.5. I need to translate that so the object would rotate 135 degrees to face down/right and move in that direction at half speed. The object is a rigidbody so ideally I'd like to use force to rotate and move since this is how it moves already.

Any help would be appreciated.

**Answer** by robertbu
·
Aug 02, 2014 at 01:47 AM

To calculate the angle, you an use Mathf.Atan2(). I believe the onscreen Joystick gives you back a Vector2. So:

```
var angle = Mathf.Atan2(v2.y, v2.x) * Mathf.Rad2D3g;
```

Note that the parameters are y,) not x,y. Also note that the angle starts at 0.0 on the right and goes *counterclockwise*, so your values of -.5 and. 5 would generate a rotation of -45 which is 315 degrees. Note if you are setting the direction of a Sprite or a Quad for a 2D game, and the front of your character is to the right, you can set the rotation like this:

```
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
```

...and the angle will match the joystick position.

You can use the magnitude of the Vector2 to scale the movement. There is a slight problem with solution. If the joystick is at an angle, the max value will be sqrt(2), where a horizontal or vertical position will produce a max value of 1.0. So you may want to cap the value at 1.0 or do some other geometry so that a diagonal movement is not faster than horizontal or vertical movement.

I had to offset the output by 90 degrees because my object is treating up as 0 degrees, but otherwise this works perfectly.

Another question. Instead of just setting the rotation, what is the proper way to add force rotation to the rigidbody until it reaches the destination angle?

### Your answer

### Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.

### Follow this Question

### Related Questions

Free fall or Jump without AddForce 1 Answer

Oblique launch problem 0 Answers

Turning a rigidbody that's in motion 2 Answers

Apply rigid body force in opposite direction of collider 1 Answer