How I created a Joystick in Unity3D
Updated 2 years ago
Get instant one-on-one help on your Unity project from community experts!
Chat with our experts on Unity Live Help to get some help on your project!
Well, first of all, this post is not intended to teach anyone on how to make a virtual joystick. I just wanted to show my approach for this simple task.
I caught myself wondering how could I do a virtual joystick in Unity... So I thought... "Why not do it using the Button component that Unity UI provides?"... It would surely work, but I also wanted an analog controller when I could control the direction of the movement. So I came up with an idea.
I could create my own Joystick component that would control the buttons (X, O, Δ, ⬜ - PlayStation controller is the best) and the analog stick. So I could only ask this component what I wanted... like... Give me the direction... Or Is the X button pressed? Stuffs like that.
Then I implemented it. I create three scripts: Joystick Controller, Button Controller and Analog Stick. The first one contains references to the other two.
The image shows the structure of the game objects for the Joystick. We'll have four Button Controller (X, O, Δ, ⬜) and the Analog Stick.

Using Event Systems interfaces would be easier than developing each functionality. Then I implemented Pointer Down, Pointer Up, Pointer Enter and Pointer Exit interfaces in the Button Controller script, in this way I can check whether it is clicked or not, and also give some visual feedback to the player.
For the Analog Stick I implemented the Drag interface. With that I can determine the direction of the movement so I could use it to move a character, a component, a camera, or any other object.
A little code and voilà.

If you want know more about how to design and implement features for your game. Do not hesitate to contact me, as a Community Expert on Unity Live Help I would be a great help for you. For now... if you want to take a look in the code, just get it on the Bitbucket:

Chat with our experts on Unity Live Help to get some help on your project!
Marcos Anderson Santos
Sotware Engineer - Programmer
Sotware Engineer
Thanks for the tip Alexander. Yes, do not require players to press exactly on the stick to start using it, would be a good improvement.
Lead Unity 3D developer
Simple and effective, I like that! But I don't think dragging interface is the best choice for stick. I'd suggest you to try one big touchable invisible object around the stick's sprite and implement OnPointerDown/OnPointerUp. Then you can easily calculate stick offset direction from PointerEventData and clamp it to max stick length.This approach do not require players to put finger exactly on the stick button to start using the stick and gives you direct control over the area where the stick can be controlled.