Hi,

I downloaded a Joystick pack on the asset store, and its incredible! But the scripts included are for a 3D game and I’m trying to code a 2D game with a joystick.

Here’s the 3D script.

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Joystick_Script : MonoBehaviour
{
public float speed;
public VariableJoystick variableJoystick;
public Rigidbody rb;
public void FixedUpdate()
{
Vector3 direction = Vector3.forward * variableJoystick.Vertical + Vector3.right * variableJoystick.Horizontal;
rb.AddForce(direction * speed * Time.fixedDeltaTime, ForceMode.VelocityChange);
}
}
```

I know to adapt this to 2D the Rigidbody will become Rigidbody2D, and I think I need to change the Vector3 to a Vector2. But I don’t quite understand how to shift the Vector3 to Vector2. Additionally, ForceMode.VelocityChange is for 3D, how do I get around this for 2D?

Thanks. Any help would be greatly appreciated!

To make a Vector3 that represents 2D movement, set the z value to 0.

To turn a Vector3 into a Vector2, use `Vector2 vec2 = new Vector2(vec3.x, vec3.y);`

ForceMode.VelocityChange will work fine for 2D or 3D. A Rigidbody2D will not allow it’s AddForce functions to add 3D force. In fact, the AddForce functions of a Rigidbody2D take a Vector2 instead of a Vector3.

Cool thanks.

I’m just a little bit confused as to the variables for the new 2D vector. I don’t understand the math behind the 3D script.

```
Vector3.forward * variableJoystick.Vertical + Vector3.right * variableJoystick.Horizontal
```

Why is the forward vector multiplied by vertical input?

In third-person 3D games, Vector3.forward is usually the direction a 3D character is facing, and you would want them to move in the direction they are facing when you tilt the control stick forward. The goal is to multiply the amount you are tilting the joystick by the direction you want to move when the joystick is tilted in that direction.

Top-down 2D might look like this:

```
Vector2 movement = Vector2.up * variableJoystick.Vertical + Vector2.right * variableJoystick.Horizontal;
```

Side Scrolling 2D might look like this:

```
bool isLookingUp = false;
if (variableJoystick.Vertical > 0.1f) isLookingUp = true;
Vector2 movement = Vector2.right * variableJoystick.Horizontal;
```

1 Like