Touch controls/ru: Difference between revisions
Godblessed (talk | contribs) Created page with "Пример общей структуры сенсорной конфигурации:" |
Godblessed (talk | contribs) Created page with "==Возможные проблемы==" |
||
Line 289: | Line 289: | ||
</div> | </div> | ||
< | <span id="Known_issues"></span> | ||
== | ==Возможные проблемы== | ||
<div lang="en" dir="ltr" class="mw-content-ltr"> | <div lang="en" dir="ltr" class="mw-content-ltr"> |
Revision as of 08:00, 7 June 2025
Сенсорные элементы управления доступны в DDNet клиенте начиная с версии 18.8, который также подмечает первый недавний релиз клиента для Android. Предыдущая версия для Android это DDNet 9.3.1 для которого существует отдельный туториал. В текущем туториале мы затронем сенсорные элементы управления для версий 18.8 и выше.
Пользовательский интерфейс может быть использован с сенсорными элементами управления следующим образом:
- Коснитесь в любом месте, чтобы переместить курсор и нажать ЛКМ.
- Коснитесь и удерживайте не менее 0.5 секунд примерно в том же месте, чтобы нажать ПКМ.
- Используйте два пальца, чтобы листать вверх и вниз прокручиваемые списки, например: браузер серверов и консоль.
- На Android: Используйте (виртуальную) кнопку Назад как клавишу Escape, чтобы закрыть меню и т.д.
Внутриигровые сенсорные элементы управления могут включаться/выключаться с помощью config variable cl_touch_controls
, который по умолчанию имеет значение 1
на Android и 0
на других платформах. Сенсорные элементы управления также работают на других платформах, которые поддерживают сенсорные устройства, но этот гайд в основном тестировался на Android.
Внутриигровые сенсорные элементы управления состоят из разнообразных кнопок, отображающихся на экране. Другие кнопки показываются только когда они могут использоваться в зависимости от случая, например кнопки для движения отображаются только в игре.
Конфигурация сенсорных элементов управления по умолчанию

Кнопки перемещения влево, вправо и прыжка расположены в ⊥
-образном порядке, похожим на WASD управление.
Для выстрела и хука реализовано два способа:
- Прямой сенсорный ввод: мышь перемещается именно туда, куда игрок прикасается на экране.
- Виртуальный джойстик: кнопка, используемая для эмуляции джойстика, которая перемещает мышь относительно центра экрана.
В другом режиме, кнопка используется для переключения между активными действиями (выстрел и хук). Когда виртуальный джойстик удерживается, эта кнопка использует другое действо напрямую, вместо переключения его.
Режим прямого сенсорного ввода может быть настроен отдельно для игры/наблюдения, чтобы предотвратить случайный прямой сенсорный ввод при использовании джойстика.
Во время наблюдения, прямой сенсорный ввод используется для панорамирования карты, например как на картинке и в просмотре карты. Виртуальные джойстики могут также быть использованы для панорамирования карты во время наблюдения.
Для перехода к предыдущему и следующему оружию отображаются две отдельные кнопки.

Кнопка меню в форме гамбургера ☰
используется для переключения видимости менее используемых кнопок. Сюда входят кнопки для отображения табло, выбора эмоций, меню наблюдателя, открытия чата и командного чата, голосования да/нет, и масштабирования. Длительное нажатие на кнопку меню в форме гамбургера откроет внутриигровое меню.
Когда дамми подключен, кнопка переключения между основным игроком и дамми отображается.
Выбор эмоций и меню наблюдателя активируются с соответствующими кнопками сенсорного управления и могут быть деактивированы нажатием за их пределами или используя кнопку Назад, поскольку переключение между ними в игре при зажатой кнопкой сенсорного управления в данный момент невозможно, а также неудобно, по крайней мере для использования меню наблюдателя.
Формат конфигурации сенсорного управления
По умолчанию расположение кнопок описанное выше загружается из файла touch_controls.json
в папке in the data
который не должен быть изменен.
Конфигурация сенсорного управления представляет собой текстовый файл в формате JSON. Рекомендуется для начала изучить основу формата JSON, чтобы понять данное руководство. Конфигурация должна быть корректным JSON файлом. Руководства и инструменты проверки JSON формата доступны в интернете. Структура JSON файла описана ниже.
The root element in the JSON file must be an object. The attribute "touch-buttons"
of the root object specifies an array of touch button objects. Each touch button object has the following adjustable properties:
- Position and size (attributes
"x"
,"y"
,"w"
,"h"
): the X/Y position and width/height are integers on a 1,000,000² grid. These unit grid values are converted to screen grid values at runtime in relation to the size and aspect ratio of the screen. This means buttons may appear stretched if the resolution is changed, but it allows us to provide a reasonable default for slightly different aspect ratios. - Shape (attribute
"shape"
): determines the shape of the button being rendered."rect"
: rectangle shape."circle"
: circle shape. The button size will automatically be adjusted so that width and height are identical.
- Visibility (attribute
"visibilities"
): an array of predefined visibility classes can be selected and the button is only shown if all conditions are satisfied. An empty array means that the button is always shown. The following visibility classes are defined:"ingame"
: player is ingame, i.e. not spectating."extra-menu"
,"extra-menu-2"
,"extra-menu-3"
,"extra-menu-4"
,"extra-menu-5"
: the extra menu with the given number is activated."zoom-allowed"
: zoom is allowed on this server."vote-active"
: a vote is currently active."dummy-allowed"
: dummy is allowed on this server."dummy-connected"
: dummy is currently connected."rcon-authed"
: player is currently authed in rcon."demo-player"
: demo player is currently active.- All visibility classes can be inverted by prefixing them with
-
, e.g."-ingame"
is satisfied when the player is not ingame, i.e. spectating.
- Behavior (attribute
"behavior"
): an object which describes the behavior of this touch button when it is activated/deactivated as well as its label. The attribute"type"
is used to differentiate which type of behavior is used. The behavior is either predefined (hard-coded) or based on generic console commands (like binds). Predefined behavior is only used where necessary, all other buttons are represented as generic binds.- Predefined behavior (attribute
"type"
set to"predefined"
): The attribute"id"
is set to a fixed string value which determines the specific predefined behavior. The following predefined behaviors can be used:"ingame-menu"
: Opens the ingame menu immediately when released."extra-menu"
: The extra menu button which toggles visibility of buttons with"extra-menu"
,"extra-menu-2"
,"extra-menu-3"
,"extra-menu-4"
and"extra-menu-5"
visibilities. Also opens the ingame menu on long press.- The attribute
"number"
specifies an integer between 1 and 5 to associate this button with the respective visibilities"extra-menu"
,"extra-menu-2"
,"extra-menu-3"
,"extra-menu-4"
,"extra-menu-5"
. If no"number"
is given, it will be set to1
automatically.
- The attribute
"emoticon"
: Opens the emoticon selector (this does not work with binds)."spectate"
: Opens the spectator menu (this does not work with binds)."swap-action"
: Swaps the active action (fire and hook) for direct touch input and virtual joysticks."use-action"
: Uses the active action with the current aiming position."joystick-action"
: Virtual joystick which uses the active action."joystick-aim"
: Virtual joystick which only aims without using an action."joystick-fire"
: Virtual joystick which always uses fire."joystick-hook"
: Virtual joystick which always uses hook.
- Bind behavior (attribute
"type"
set to"bind"
). Buttons with this behavior execute console commands like regular key binds.- The attribute
"label"
specifies as a string the label of the button. - The attribute
"label-type"
specifies as a string the type of the label of the button, i.e. how the attribute"label"
is interpreted:"plain"
: Label is used as is. If no"label-type"
is given, it will be set to"plain"
automatically."localized"
: Label is localized. Only usable for the default buttons for which there are translations available."icon"
: Icon font is used for the label. Icons must be encoded in UTF-16 using\uXXXX
, e.g.\uf3ce
for the mobile phone icon which has unicodef3ce
. Note that the icon must be available in the icon font that comes with DDNet, Font Awesome Free.
- The attribute
"command"
specifies as a string the command to execute in the console like a bind when this button is used, e.g."+fire"
for a button that uses the fire action.
- The attribute
- Bind toggle behavior (attribute
type
set to"bind-toggle"
). Buttons with this behavior cycle between executing one of two or more specified commands.- The attribute
"commands"
specifies an array of two or more commands in the order in which they are shown and executed. Each command is an object with the attributes"label"
,"label-type"
and"command"
which are defined the same as for the bind behavior described above. At least two command objects must be specified in the array.
- The attribute
- Predefined behavior (attribute
The root object additionally has the following attributes:
"direct-touch-ingame"
: specifies the mode of direct touch input while ingame. Possible values:"disabled"
: Direct touch input is not used while ingame. This means a virtual joystick is necessary."action"
: Direct touch input uses the active action (see above)."aim"
: Direct touch input only changes the aiming position without using an action. This means separate buttons for using the actions are necessary."fire"
: Direct touch input always uses fire."hook"
: Direct touch input always uses hook.
"direct-touch-spectate"
: specifies the mode of direct touch input while spectating. Possible values:"disabled"
: Direct touch input is not used while spectating. This means a virtual joystick is necessary."aim"
: Direct touch input is used for spectating.
"background-color-inactive"
(added in DDNet 19.0): specifies the background color of inactive touch buttons. See details about the color format below."background-color-active"
(added in DDNet 19.0): specifies the background color of active touch buttons. See details about the color format below.
Color format
Colors are specified as hexadecimal strings in the formats RRGGBBAA
, RRGGBB
, RGBA
and RGB
without any prefix like #
, e.g. "A526C440"
. If the alpha value is omitted then it is set to full opacity by default.
Ingame menu buttons

In addition to the separate on-screen touch controls, a second row is added to the main page of the ingame menu when cl_touch_controls
is enabled for less frequently used functions which are otherwise not usable without a keyboard:
- Buttons to open the local and remote consoles. Opening the local console without the touch controls is useful because error messages would be shown there if the touch controls configuration could not be loaded.
- Button to close the menu, which is more convenient than using the virtual back button if it's not always shown.
- Checkbox for toggling the touch controls editor UI (see below).
Ingame touch controls editor

The user interface to adjust the touch controls is rendered over the main screen of the ingame menu when enabled. For now, the touch controls editor is limited to basic configuration management functions.
- Saving the configuration to the
touch_controls.json
file in the config directory. - Discarding the current changes by reloading the
touch_controls.json
file from the config directory. - Restoring the default configuration by reloading the
touch_controls.json
file from the data directory. - Displaying whether there are unsaved changes.
- Importing and exporting the configuration from and to the clipboard. This is the only way to edit the configuration on newer Android versions, as editing files within apps' storage is not possible anymore.
Furthermore, the global touch controls settings can be adjusted in this UI:
- The direct touch input modes while ingame and spectating (see Touch button configuration format) can be adjusted using dropdown menus.
While the touch controls editor is active, all touch buttons are shown regardless of their visibilities, to better support arranging the buttons.
Adjusting the controls
- Export the touch configuration to the clipboard.
- Save the clipboard to a file so you can more easily edit it. You should also do this to have a backup of your configuration!
- Edit the configuration (see above for details about the format).
- Copy the edited configuration to the clipboard and import it in the client again. If the configuration could not be loaded successfully, check the local console for error messages containing
touch_controls
and fix the configuration accordingly. Use online tools for JSON validation and formatting. - Save the changes in the client when you are done. You can also discard your changes or revert to the default if you messed up.
A more convenient user interface to edit the touch controls directly in the client is planned.
Note: You can also edit the file touch_controls.json
in the config directory directly instead of exporting/importing to/from the clipboard, but this is not supported on Android.
Примеры
Пример общей структуры сенсорной конфигурации:
{
"direct-touch-ingame": "action",
"direct-touch-spectate": "aim",
"background-color-inactive": "00000040",
"background-color-active": "33333340",
"touch-buttons": [
...
]
}
Example button with "bind"
behavior that echos a message in chat:
{
"x": 500000,
"y": 500000,
"w": 100000,
"h": 100000,
"shape": "rect",
"visibilities": [
],
"behavior": {
"type": "bind",
"label": "Example",
"label-type": "plain",
"command": "echo Hello world!"
}
}
Example button with "predefined"
behavior for a virtual joystick that uses the active action:
{
"x": 755000,
"y": 580000,
"w": 225000,
"h": 400000,
"shape": "circle",
"visibilities": [
"ingame"
],
"behavior": {
"type": "predefined",
"id": "joystick-action"
}
}
Example button with "bind-toggle"
behavior that switches between echoing three different messages in chat:
{
"x": 600000,
"y": 200000,
"w": 100000,
"h": 100000,
"shape": "rect",
"visibilities": [
],
"behavior": {
"type": "bind-toggle",
"commands": [
{
"label": "Echo 1",
"label-type": "plain",
"command": "echo 1"
},
{
"label": "Echo 2",
"label-type": "plain",
"command": "echo 2"
},
{
"label": "Echo 3",
"label-type": "plain",
"command": "echo 3"
}
]
}
}
Возможные проблемы
- Problem on Android: Pressing down 3 or more fingers at the same times causes all fingers to be released immediately.
- Solution: This is caused by features of your phone that handle global gestures with multiple fingers. Open the Settings app and disable gesture features that involve 3 or more fingers (search for "3 fingers"). In particular, disable the "Swipe down with 3 fingers to take screenshot", "Touch and hold with 3 fingers to take screenshot" and "Swipe up with 3 fingers to enter Split View" features.
- Problem on Android: Rarely, touching in the top around 15% of the screen does not work at all or very inconsistently.
- Solution: It is unclear what causes this. It should be fixed by restarting the app. Going back to the home screen may also fix it.
Implementation details
These are details about the implementation of the touch controls intended for developers.
The ingame touch controls are implemented in a separate client component CTouchControls
in the files src/game/client/components/touch_controls.cpp
and src/game/client/components/touch_controls.h
. Whenever possible, binds are used directly as button behavior instead of using predefined behavior to reduce complexity.
When adding your own button behavior in a forked client it is recommended to prefix names of new shape, visibility, behavior etc. with the name of your fork, e.g. myfork.octagon
if you add a new shape for octogonal buttons, to prevent conflicts in future versions.
To add touch support for other ingame client components like the emoticon wheel and spectator menu, use the CUi::UpdateTouchState
function like for the emoticon wheel and spectator menu. Ensure that your component handles KEY_ESCAPE
to close itself, which also corresponds to the Back-button on Android. Note that only one component may use the touch state in each frame, so it is not possible to hold an ingame touch button and use another component like the emoticon wheel at the same time with other fingers. Instead, the respective predefined touch button behavior (e.g. CSpectateTouchButtonBehavior
) only activates the ingame component (e.g. the spectator menu) in its OnDeactivate
function but does not deactivate it again. Activating the component in the OnActivate
function already would cause the finger that activated the button to also affect the activated component.
References
- Default touch button configuration: https://github.com/ddnet/ddnet/blob/69c92a79e6bab9f9390245f518c5340222c544dc/data/touch_controls.json
- Pull Request adding Touch controls to engine and UI: https://github.com/ddnet/ddnet/pull/8621
- Pull Request adding Ingame touch controls: https://github.com/ddnet/ddnet/pull/8632
- Pull Request adding Emoticon and Spectate touch controls: https://github.com/ddnet/ddnet/pull/8801