The joystick controller is the most used controller to move players in-game. Today we will be creating a joystick with a touch area control that can be enabled and disabled while playing.
We can divide this process into 2 steps.
UI Setup in Unity Editor
Scripting
UI Setup in Unity Editor
Create a canvas from the Unity UI. In the newly created canvas, create an image from UI > Image and give it the name JoyStick. This GameObject will have a joystick script, and its image area will determine the touch area for the joystick.
Inside JoyStick, create another empty GameObject with the name JoyStickParent. This gameObject will be used to enable and disable the joystick.
Inside JoyStickParent, create another image from UI > Image. Name this image OuterCircle and change both its height and width to 300.
Inside OuterCircle, create another image and name it InnerCircle. Set both height and width of this image to 150.
Now, set the Rect Transform of InnerCircle and OuterCircle to the centre.
Scripting
Now that we have the UI of the joystick set let's move on to making it actually work. For that, we will need to create a joystick script and a JoystickReader script.
joystick Script
This script will read the user input, set the position of outerCircle and innerCircle, and has action onJoyStickMoved which provides our input as vector2.
Make sure to read the code comments to see how the code works.
Now attach this script to the JoyStick GameObject in canvas.
JoystickReader Script
This script will get the input of the joystick as vector2. Then, we can use it to move the player or move the camera, whichever is required.
Create an empty GameObject outside the canvas in the editor and name it as JoystickReader. You can now attach the script shown below to the newly created GameObject. Now, when we play this game, we will see the input value in JoystickReader's component as we touch or press in the white image area of JoyStick .
This is how we read input from the JoyStick class. We get values (0,1) when the joystick moves right and (-1,0) when the joystick moves left.
That's all for now and I hope you learned a new thing today! Stay tuned for the next one.