- Управление свайпами в игровом проекте на Godot Engine
- Godot 3.1 – How to export to Android in simple steps
- Installing the export templates
- Downloading Android SDK and the JDK
- Creating a key using the command line
- Navigating to the Android export editor settings
- Setting up the location for the Adb
- Setting up the location for the Jarsigner
- Setting up the location of the Debug Keystore
- Getting ready to make a build
- Making your build
- Releasing the build to Google Play Games
- How to make a release keystore?
- Set the reference in the export
Управление свайпами в игровом проекте на Godot Engine
Всем Приветствие! Сегодня я бы хотел рассказать о том, как реализовать управление свайпами в игровом проекте для Android на движке Godot Engine.
Меня зовут Пётр, и я являюсь одним из активных пользователей игрового движка Godot Engine.
В русскоязычном сегменте огромнейший дефицит материалов по данному инструменту, что меня сильно удивляет, так как он является одним из самых быстро-развивающихся игровых движков.
Конечно, он во многом уступает таким движкам, как Unity, UE, и подобным, да и игру класса «AAA» на нём не сделаешь.
Однако! Он бесплатный (полностью), кросс-платформенный (полностью), а его вес составляет порядка 60 мегабайт, в противовес тому же Unity.
Движок запускается на большинстве устройств, даже если последние из совсем уж бюджетного ряда. Так же «из коробки» он уже русифицирован, имеет на борту все необходимые инструменты, не требует наличия дополнительного ПО, и не съедает в запущенном виде всю оперативную память.
На Хабре я уже видел пару статей по нему, и это очень мало, так как он настолько дружелюбен к разработчику, что пройти мимо него и не попробовать — большое упущение.
Тема данного поста — реализация управления свайпами (жестами) в Android-проекте.
Вообще, опыт моего использования движка довольно обширен, и, если тема получит отклик, я могу оформить целый обучающий курс. Данным же постом я хочу хотя бы немного привлечь ваше внимание к движку.
В качестве языка программирования можно использовать, опять же, из коробки, два варианта: GDScript и C#. Я буду использовать первый.
Интерфейс основного редактора выглядит так:
В нем можно работать одновременно с 3D, 2D, скриптами и вообще всем, что может потребоваться разработчику.
В движке используется подход, при котором ваша игра представляет из себя набор сцен, вложенных друг в друга. И тут может возникнуть некоторая путаница, потому термин «сцена» я использую для узлов, которые представляют из себя именно игровые сцены (ситуации, окна, состояния игры (меню, игра, т.д.)), а для остальных случаев я использую термин «префаб», позаимствованный у Unity.
Поскольку в данном посте я буду рассматривать частный случай, то и разворачивать некоторые темы я не буду. Если что-то неясно — есть комментарии.
Так вот, основной сценой для демонстрации у нас будет game.
Структура её выглядит так:
Корневой узел game хранит в себе вложенные:
— world, — хранит в себе данные уровня
— — level, — набор объектов окружения (блоки, кольца, препятствия)
— — player, — объект игрока
— — InterpolatedCamera, — плавная камера, следящая за игроком
— gui, — интерфейс, задействован не будет
Имена объектам и структура произвольная и это только частный случай.
Возле некоторых объектов вы можете видеть значки, говорящие о том, что этот объект является префабом (вложенной сценой) и у него так же может быть добавлен скрипт.
Так, нажав на значок «скрипт», мы попадаем в редактор сценариев, по сути просто переключается режим работы движка.
В данном режиме работы можно редактировать поведение объектов. Собственно, в данном случае это скрипт объекта world, который при загрузке объекта в игру устанавливает в объект камеры (InterpolatedCamera) устанавливает цель для слежения.
Синтаксически GDScript похож на Python. Пройти краткое обучение GDScript на русском языке можно тут: GDScript Book
С объектом world понятно, он просто устанавливает камере цель для слежения. Следующий объект (уже дочерний для world), — это level. Его структура выглядит так:
По сути, это просто расставленные объекты с физическими свойствами, не имеющие скриптов и поведения. Кроме объектов «cell». Это вращающиеся колечки, исчезающие при соприкосновении с объектом игрока.
Больше всего сейчас интересен объект player, в котором содержится логика управления свайпами для сенсорных экранов.
Выглядит данный префаб так:
Корневой объект имеет скрипт, к которому мы перейдем немного позже.
Сначала рассмотрим вложенные объекты.
- camera, — тот самый указатель для камеры, которая будет плавно к нему стремиться, дабы сгладить движение. Не имеет никакого поведения и просто существует в рамках объекта player.
- CollisionShape, — это физическое тело объекта. Именно он реагирует на столкновения и позволяет «осязать» объект. Для примера я выбрал его в виде куба, хотя поддерживаются самые разные формы, вплоть до произвольных. По сути для физической формы объектов ограничений нет совсем.
- MeshInstance, — это визуальное представление объекта. В данном случае это шар, покрытый текстурой. Сделан в Blender 3D меньше, чем за минуту.
- Tween, специальный аниматор для плавных изменений численных свойств объектов. Он отвечает за анимированные сдвиги влево и вправо при свайпах.
Ну и теперь рассмотрим уже сам скрипт в корневом объекте. Он получается самым объемным во всей «игре».
Ну и его описание и расшифровка.
Каждую строчку описал, надеюсь, со скриптами всё плюс минус ясно.
Если русским языком, то мы при движении пальцем по экрану регистрируем направление движения и скорость. Если палец движется с нужной скоростью, засчитываем свайп. Исходя из того, по какой оси и в какую сторону шло движение, имеем три вариант: ВВЕРХ, ВЛЕВО, ВПРАВО.
Записываем полученное значение в переменную, которую тут же подхватывает событие обновления состояния объекта, и выполняет с ним нужные действия, после чего помечает событие, как отработанное и ожидает следующее.
Я взял не самый простой способ реализации свайпа, однако довольно надежный и работающий в большинстве ситуаций. Само собой, зависит от жанра и типа игры.
В результате проделанной работы мы получаем пример того, как легко реализовать управление свайпами буквально за десять минут.
Суммарно на всё у меня ушло минут 30, это с учетом создания моделек в Blender.
Источник
Godot 3.1 – How to export to Android in simple steps
Building and setting up the export for Android in Godot can feel a bit intimidating for newcomers, however you only have to do this once. Afterwards you are able to send a build to your mobile device in a matter of seconds, by just pressing a button and having a mobile device attached through USB.
The first thing you have to do in Godot is ensure you have the Export Templates setup. You can do this by going to Editor/Manage Export Templates in Godot. Afterwards you click on the download button. Afterwards you go to Editor/Editor Settings select the Export tab, and Android. From there you can set the locations for the Adb, Debug Keystore and Jarsigner locations. You can get the Adb from the Android SDK, the debug keystore is made using the JDK keytool which is downloadable through Github or Oracle.
Installing the export templates
In order to install the export templates, navigate to the top window and select Editor. From there you can select Manage Export Templates. Afterwards you click on the download button like the image below. And you then select Official 3.1.2 [HTTPS]. Note that this can change based on the version you are currently using of Godot. Sometimes when the link is not available, you have the option to install a template through a file. You can find older export templates and releases here. You can also get the latest Github release with export templates on the Unofficial Godot Engine builds site by Hugo Locurcio. Do note tough that the export template needs to match the current Godot version.
The images below show you how to do it visually.
Here you can see how to navigate to the Manage Export Templates selection
After opening the Export Template Manager menu, click on Download
Installing the export templates using the official link
After the download is done, the export templates get installed automatically. Kind in mind that you will have to repeat this process for each new version you have to install. This step is fairly easy tough, I think we can manage this.
Downloading Android SDK and the JDK
In order to setup these things you have to download the Android SDK and you have to download OpenJDK or OracleJDK. It is recommended to stay at JDK version 8 or higher, as lower versions may have issues. I personally installed java-1.8.0-openjdk, the third option on the OpenJDK github page.
Creating a key using the command line
After you have installed both the SDK and OpenJDK. You should be able to use this command with the command line. For windows you can go to the command like by opening the search bar (pressing the windows button) and searching for CMD and pressing enter. You can then copy the following command into the command line.
For Windows 10, you can then find the keystore in “C:\Users\YourUserName”, it is named “debug.keystore”. Make sure to keep the folder to this location available, since we will need it later on.
If you are certain you have installed both the JDK and SDK and the command does not work due to it not being recognized, then there is a chance the system variables are not setup properly. You can find a guide here that shows you how to point the system variables to the JDK folder.
Navigating to the Android export editor settings
In order to start setting up the references, you have to navigate to Editor/Editor Settings
As you can see, the Editor Settings is located under the Editor tab
Afterwards, you scroll down on the left side until you get to the Export tab, and you select Android
All the settings for the Android Export
Setting up the location for the Adb
For Adb you have to go to the SDK folder and then into the “platform-tools” folder. For windows 10 this is generally located at:
If you are unsure where to find the Sdk folder, open up the Android SDK and navigate to the new project settings like the image below.
Example of how to find the android Sdk location on your computer using Android Studio
Setting up the location for the Jarsigner
The Jarsigner is located in the OpenJDK or OracleJDK folder you have unpacked previously.
When installing the OpenJDK on my device it was located at:
Setting up the location of the Debug Keystore
This keystore was made earlier in this article, once created, it gets placed in the User folder:
Getting ready to make a build
Navigate to Project/Export to go to the export window
Add a new export preset by pressing the Add… button and selecting Android
How to add a new present in the export options
Now finally, set the Unique name and name of the package.
How I generally name the Unique name is com.myComp.ProductName and the name is what will be displayed on your android device. So that should be equal to your product name. Spaces are allowed.
How to setup the package Unique name and general name
Making your build
There are two ways to make a build. One is to press the Export Project button in the export window. The other option is to use the icon that is available in the editor window. Personally I prefer using the icon, as this will automatically install the build to the phone. Just make sure it is connected to your computer using USB with USB Logging on, using developer mode. If you are unsure how to enable developer mode. Then you have to google “How to enable developer mode ”.
How to quickly build the project to your device
After pressing the button above, you will have the game running in no time on your device.
Releasing the build to Google Play Games
When exporting a build to Google Play Games, it is important to use a release keystore. This is because the debug keystore is merely meant for development and testing purposes. It is also not advised to release games using a debug keystore.
Signing a keystore is like branding the application with your credentials. And it is possible to assign the same keystore to multiple applications. The debug keystore has base credentials.
Eventually when you want to release to the play store you use a Release keystore. It is important that you keep this key safe, since you will only be able to push updates if you sign the application with the initial key. Preventing malicious users from pushing harmful code in case the account gets stolen.
How to make a release keystore?
Again, like the steps above to create a debug key, there is a parameter to create a release key. Make sure to set yourKeyAlias to an alias of your choice.
After doing this, you will get the question for a password. Make sure to note it down, because losing it means losing your key. And it has happens to people before that they had to republish a game on Google Play due to this.
After entering the password twice, you will get a lot of questions such as first/last name. Organisational unit, etc. You can leave these blank. At the end you get a question asking if it is all correct, you then type in yes. After creating the key, you may get this message:
Doing this will change the keystore into a file with the “.pfx” extention, from what I’ve seen godot only accepts the .keystore format. So we can ignore this for now.
Set the reference in the export
Finally we set the reference to our release key in the export like the image below.
Also, when you have pressed export, do not forget to toggle this off, else it will still sign it using the debug key!
Thank you for reading, and I hope it has helped you. If you have interest in implementing ads into your game and you happen to be using Godot 3.2, then I recommend reading “How to integrate Google Ads (Admob) for Android”
Источник