Создание виртуального джойстика на юнити (основная статья)
Всем привет! В этой статье мы будем делать простой виртуальный джойстик на юнити.
Виртуальный джойстик (в дальнейшем буду называть его просто джойстик) — это крайне полезная вещь почти в каждой мобильной игре. С его помощью вы можете управлять движением персонажа, или сделать простое прицеливание, если вы делаете шутер.
Работа джойстика крайне проста — есть специальная «ручка» которую игрок двигает пальцем в определенной зоне. Когда нам нужно скажем, передвинуть персонажа, мы обращаемся к скрипту джойстика и он возвращает нам смещение ручки относительно одной или двух осей.
ВАЖНО! Смещение должно быть нормализованным. То есть максимальное значение по любой оси не должно быть больше единицы, а минимальное — минус единицы. Иначе будет трудно настроить ту же скорость движения персонажа. Например, нам нужно чтобы персонаж двигался с максимальной скоростью 3 метра в секунду. Если смещение будет нормализованным, то максимальная скорость персонажа будет равна заданной, то есть 3 м/с, если же оно не будет нормализованным, то скорость может быть равна, например 8 или 0,2 или 114 м/с.
Итак, приступим. Для начала нам нужно пару кругляшков для обозначения «зоны» и «ручки». Нарисовать их можно в фотошопе или где-нибудь ещё и экспортировать в юнити.
На сцене создаем канвас, создаем в нем объект с компонентом Image, кидаем в свойтво source image наш спрайт зоны и ставим в нужное место на экране. Готово! Это наш джойстик. Затем создаём скрипт управления джойстиком и вешаем на него. Далее создаем джойстику дочерний объект с тем же имаджем (не бейте пж за мой английский) и кидаем на него спрайт ручки. Это наша ручка (как ни странно).
Самая скучная работа закончена и можно начинать кодить.
Итак, прежде всего нам нужно отслеживать взаимодействие пользователя с джойстиком. Для этого будем использовать интерфейсы IDragHandler (для отслеживания «перетаскивания» джойстика пальцем) и IEndDragHandler (для того, чтобы знать когда пользователь убрал палец с джойстика). Объявляем класс наследником этих интерфейсов и реализуем их. Наш код должен выглядеть примерно так:
ВАЖНО! Обязательно добавьте CircleCollider2D на джойстик для регистрации нажатий по нему и не забудьте сделать его триггером. На основную камеру добавьте Physics 2D Raycaster для того чтобы узнавать о клике пальцем на джойстик.
Далее, нам нужно двигать ручку за пальцем. Для этого модифицируем наш скрипт:
Ок, теперь ручка теперь двигается за пальцем, но её движение нужно ограничить определенным радиусом. Порывшись в документации к юнити и попробовав пару костылей я нашел самый простой на мой взгляд способ сделать это.
Это Vector3.ClampMagnitude. Этот метод возвращает обрезанную до определенной длины копию вектора. То что нам и нужно. Модифицируем код.
Заключительные шаги. Теперь сделаем то, зачем мы все это затеяли. Получение направления от ручки до центра джойстика.
ВАЖНО! В коде ниже будут использоваться свойства. Почитайте, что это такое (если вы не знаете) чтобы понимать, что там происходит.
Это финальный скрипт. Больше мы не будем его дорабатывать.
P.S. Выше я использовал свойство, только затем, чтобы сэкономить пару операций и не изменять значение каждый кадр. А static я использовал, чтобы получать значение проще. Вот пример:
Так как статья получается довольно длинной, то различные модификации джойстика я не буду публиковать здесь. Для этого я создам отдельную статью, которая выйдет сегодня или (если мне будет лень) завтра.
Если вы хотите увидеть реализацию какой-нибудь другой механики в блоге, то пишите в комментариях. Также буду весьма раз фидбеку.
Mobile Virtual Joystick Movement with Unity’s Input System
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.
Name already in use
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Sep 1 : Intruction to Virtual Joystick
Everdered how your soldier moves in Mini Militia? Want to know how shadow moves around and battles in Shadow Fight series? Have a Desire to achieve player control like Bloody Harry? Or just excited to learn about Virtual Joysticks?
Then your search ends here.
In this blog, I will show you how to implement a virtual joystick in Unity. Now, keep your favourite joystick design in your mind and follow the simple steps.
And you will have your own working model of Virtual Joystick right in your hands or rather I would say, right under your thumb!
Step 2 : Scene Setup
Setup your scene as shown in following pictures:

For now, I’m using a simple 2D image to represent our player.
Do not forget to set anchor point and pivot point for your Joystick Container, or you will find your joystick on different positions on different resolutions.

Step 3 : Scripting
Attach this script to JoystickContainer
Notice that we are using EventSystem namespace here to handle touch events in our project.
As Unity Docs would say,
Let’s dive in our methods now:
1 — OnDrag(): It passes one argument of type PointerEventData. This class is associated with mouse and touch events. We will only need a couple of values from it, so I’m skipping the description. Still if you want to check all the description about it, follow this link:
-
The function RectTransformUtility.ScreenPointToLocalPointInRectangle returns true if the RectTransform of gameobject is interacted. And also gives the location of the point of interaction.
After that we’ve calculated the Input Direction and the position of our joystick.
2 — OnPointerDown(): This is used to invoke OnDrag() method. This will allow us to get the effect as soon as we touch/click our joystick, even if we are not dragging the stick. Remove this invocation and see the difference in behaviour in play mode.
3 — OnPointerUp(): It sets InputDirection and joystick position to zero.
Attach this script to player gameobject.
Dont’t forget:
- Assign the JoystickContainer gameobject to jsMovement in editor before you hit play.
This script has only one method. Update(). Which gets the InputDirection from our previous script and moves our player according to it.
Now hit Play and see how well your joystick handles your player. I Hope now you got the basic idea about joysticks.
Now you can create joysticks with your own awesome graphics and excellent concepts.
[Unity] How to Configure The Virtual Joystick and Move Object

In the last year, I tried to use Unity to make a 2D bird’s-eye view sooting game. At that time, I tried to download virtual joystick package in the Unity store, but the move effect was not satisfactory. I recently studied the production of mobile games, and find making the virtual joystick by myself is unexpectedly easy.
For the convenience of demo, the virtual joystick does not use any image and uses Unity’s built-in assets, so it may be a bit crude.
Virtual Joystick
Step 1: Create the Canvas and Image object
Click right button to create Canvas and Image object from UI options.

And place them to be the following architecture:

Set the anchor point of JoystickContainer Image to the lower left corner. This step is very important, otherwise the joystick operation will fail later. If you want to know, the pivot of this object I set x=0.5 and y=0.5.

Step 2: (Optional) Add color for object
You can skip this step.
I just want everyone to know which is the joystick and which is the player’s object.

Step 3: Write the script
Joystick.cs (Attach to Image-JoystickContainer object)
Player.cs (Attach to Image-Player)
Step 4: Attach the Image-JoystickContainer object to the jsMovement field of the Image-Player object

Step 5: Play!
The above is the introduction of how to make a virtual joystick by yourself in Unity.