Mobile Virtual Joystick Movement with Unity’s Input System
Let Your Fingers Do the Walking
I’m making a 2D mobile adventure game. The features are all complete, but until now, there hasn’t been anything particularly mobile about this game. It’s time to fix that, by enabling on-screen joystick and buttons for mobile touch input.
My game is using the Unity Input System package, which has a pair of very easy-to-use scripts for on-screen touch input. If you are looking for a guide to setting up the Input System package and building a character controller with it, you can see my previous article on the topic.
First we’ll look at the joystick.
Movement Stick
The first thing I need is a UI canvas image to represent the joystick. It’s best for this to be circular, but any shape or design will work.
Because mobile screen sizes vary, it’s important to anchor your controls in the corners of the screen. This will keep the button from appearing in strange places.
From there, we need to add the On-Screen Stick script component that came with the Input System package.
Finally, set the Control Path dropdown on this component to be the same as your control for movement in the Input Action asset — in my case, this is the “Left Stick [Gamepad]”.
This is all that is required. The Input Action system already knows what to do with the Left Stick, and my character controller doesn’t care what control system we use so long as it gives Vector2 data.
Button Input
This time we’re going to create another UI image for each button. Again, any image will work, here. It does not need to be a UI Button, and we won’t need an OnClick event. Also, make sure to anchor the images into the lower corner.
Once your images are set up, add an On-Screen Button script component to each.
As before, set the Control Path to match an already established path from your Input Actions asset.
And that’s it! We now have instant compatibility with any touch-screen device with almost zero fuss.
That’s all for this article. And that wraps up all the features for this game! Tomorrow we’ll do an overall progress review and talk about the next project.