Готовый город для unreal engine 4

  • Разработка игр
  • Приветствую, Хабр! Хотел бы познакомить вас с относительно небольшим проектом, который я сделал c нуля примерно за 150 часов (50 заходов ~3 часа каждый) на Unreal Engine 4. Проект я делал в прямом эфире только на стримах раз в неделю (в общей сложности ушел год), попутно отвечая на вопросы пользователей.

    Сам проект не предназначался как коммерческий. Целью я ставил на практике показать всю сложность разработки игр, а именно такие проблемы, как:

    • Планирование и прототипирование проекта
    • Продумывание и реализация архитектуры проекта и отдельных его компонентов
    • Реализация интерфейса пользователя
    • Отладка и исправление ошибок
    • Работа с ассетами и графикой

    В конце всей серии стримов у нас получился играбельный прототип “Сурвайвл” шутера. Те, у кого стакан наполовину полон, смогут даже назвать это пре-альфой без сюжета.

    Если вам интересны подробности проекта, записи стримов, исходники и прочее, читайте далее.

    Весь проект был реализован на визуальной системе программирования, под названием “Блупринты”. И конечно многие спецы могут назвать её ребяческой, разработать на ней можно спокойно даже относительно крупный проект. Более того, это можно сделать относительно быстро, как мы уже смогли доказать.

    Сразу хочу ответить на вопрос: "Почему Блупринты, а не С++? ". Ну во первых, когда я начинал серию, плюсы я почти не знал. Хотя я и сейчас подобный сингл делал бы на БП. Во вторых, БП почти не уступают плюсам в нашем случае, но при этом дают ряд возможностей: Не позволяют наделать множество ошибок, возможных с плюсами, не приходится отвлекаться между БП и С++, понятнее новичкам. Да и они в нашем случае не намного медленнее, учитывая тот факт, что почти вся логика построена на событиях.

    Мы так же успели немного поработать над графикой. К сожалению, ассеты делать времени у нас не было, поэтому мы часть оставили пустышками, часть сделали прямо в редакторе из примитивов, а некоторый контент позаимствовали из бесплатных демок Epic Games. Тем не менее, что-то успели сделать и сами, например систему дня и ночи, постобработку для воды и некоторые материалы объектов сцены.

    В планы моих стримов так же стояли и проблемы, которые могут возникнуть при разработке. Их я специально решал в прямом эфире, дабы не только показать, с чем могут столкнуться юные разработчики, но и как отлаживать свой код, искать баги и писать свой код так, что бы все это дело можно было делать в два раза быстрее. Конечно опыта в программировании у меня не десятки лет, и это сказывалось на том, какие порой глупые ошибки я делал. Да и уверен, что многие разработчики могут оспорить множество моментов в процессе написания игры.

    Естественно, полноценной игрой это вряд ли можно назвать, так как нету ни сюжета, ни цели в игре - только чистая механика. Тем не менее, я считаю, что результатом можно гордится и он вполне отражает то, для чего задумывался весь проект.

    Список всего, что мы успели реализовать в нашей игре

    Персонаж

    • Управление персонажем
    • Система жизненных показателей (Жизни, броня, стамина, голод, жажда)
    • Переключение вида (от первого лица и от третьего)
    • Моделька (сделали во Fuse, анимации взяли с Mixamo)
    • Настроенные анимации передвижения и использования оружия
    • Универсальное взаимодействие с предметами

    Объектная система инвентаря

    • Компонент инвентаря (встраивай в любой объект, куда хочешь)
    • Клеточная система с поддержкой различного размера предметов
    • Размер инвентаря по клеткам на страницу и по весу.
    • Класс предметов, которые можно положить в инвентарь. Предметы хранятся в качестве объектов.
      • Вес, размер, информация, состояние предмета
      • Функционал для стака (когда в одной ячейке много одного предмета)
      • Возможность добавить логику использования предмета
      • Выбрасывание из инвентаря
    • Интерфейс для взаимодействия с инвентарем
    • Интерфейс для обмена между другим компонентом и своим.
    • Drag&Drop манипуляция объектами между инвентарями и внутри одного.
    • Контекстное менюу предметов
    • Подсказки при наведении на предметы в инвентаре и в мире.
    • Список генерируемых предметов при создании объекта с компонентом / начале игры.
    • Список начальных предметов при создании объекта с компонентом / начале игры.
    • Система торговли между другим инвентарем
      • Интерфейс торговли
      • Компонент менеджмента денег (необходим для работы торговли)

    Система экипировки

    • Экипировка нескольких типов предметов: Шляпы, Топ, Брюки, Ботинки, Оружие
    • Скелетная синхронизация у Топа, брюк и ботинок. (Шляпы и оружие по сокетам)
    • Удобное окошко для экипировки с поддержкой Drag&Drop
    • Поддержка логики-модификаторов при одевании
    Оружие
    • Дальнобойное оружие
      • Перезарядка
      • Использование предметов-патронов из инвентаря
      • Поддержка классов снарядов/пуль
      • Автоогонь/одиночный огонь
      • Отдача с разбросом (свой + от факторов, н.п. бег или приседание)
    • Холодное оружие (с несколькими видами проверок на урон на выбор)
    • Состояние оружия ухудшается при использовании
    Система крафта
    • Крафт по рецепту (выбрал рецепт, он скрафтил, аля фоллаут)
    • Крафт по предметам (закинул нужные предметы, он скрафтил, аля майнкрафт)
    • Интерфейс пользователя только для второго типа крафта.
    Агрессивные мобы
    • Мобы ближнего боя (если увидят, побегут и начнут бить)
    • Мобы смешанного типа (стреляют, но если достаточно близко, побегут что бы ударить)
    • Дальники оббегают препятствия, если не могут выстрелить.
    • Есть встроенный инвентарь для лута после убийства.
    • Зона спауна
    • Список классов
    • Шанс спауна
    NPC
    • Городские NPC, патрулирующие свою зону спауна
    • Уникальные NPC
    • Базовый контроллер расписания для уникальных НПЦ
    • Реакция на урон (убегают или используют имеющееся оружие)
    • Встроенный инвентарь для лута после убийства.
    • Объектная диалоговая система
      • Дерево диалогов
      • Каждый ответ - объект
      • Для каждого ответа можно докинуть любую логику или условие доступности.
      • Интерфейс диалога
      • Несколько готовых классов ответа (запускает торговлю, забирает ресурсы, если есть, выходит из диалога)
    Строительство
    • Класс конструкций, которые поддерживают размещение
    • Использование предметов-ресурсов из инвентаря при размещении.
    • Снаппинг на некоторых типах конструкций (н.п. Стены, фундамент, окна)
    • Менюшка с конструкциями
    • Подсвечивание конструкций, на которые хватает ресурсов
    Дополнительно
    • Небольшая карта с городом, лесом, водоемами (можно плавать).
    • Система смены дня/ночи
    • Автомобили
      • Вид от первого или третьего. Общее с персом
      • Включение/выключение фар.
      • Встроенный компонент инвентаря (нужно взаимодействовать у багажника)
    • Кое как работающие лестницы вертикального типа.
    • Главное меню
    • Меню паузы
    • Меню с настройками графики

    Впрочем, говорить о проекте можно бесконечно. И чтобы не превращать статью в книгу, предлагаю ознакомиться с игрой и возможностями по видео. А тем, кому стало действительно интересно, чуть ниже сможете найти записи всех стримов, ссылки на исходники и билд игры.

    Содержание по частям

    1. Начинаем и планируем проект. Создаем управление и поведение персонажа.
    2. Начинаем делать систему инвентаря.
    3. Продолжаем делать базу системы инвентаря.
    4. Готовим базу для экипировки и вооружения.
    5. Работа над оружием и использовании патронов.
    6. Делаем автострельбу и прицеливание.
    7. Создаем базовую систему крафта.
    8. Бег, переработка предметов и их износ.
    9. Реализовываем перезарядку для оружия.
    10. Делаем оружие ближнего боя.
    11. Доделываем ближний бой и делаем лестницу по которой можно взбираться.
    12. Делаем интерактивные предметы: Дерево, камень, кусты.
    13. Делаем HUD и начинаем делать интерфейс для инвентаря.
    14. Продолжаем работать над интерфейсом инвентаря. Делаем генерацию ячеек с предметами.
    15. Продолжаем делать генерацию ячеек и поиск места для предмета. Добавляем страницы инвентаря.
    16. Делаем небольшое взаимодействие с предметами в инвентаре и окно подробной информации.
    17. Сделали Drag&Drop перетаскивание предметов по инвентарю и в другой инвентарь.
    18. В этой части речь идет о визуализации крафта.
    19. Создаем окно с выбором количества предметов из стака для переброса в другой инвентарь.
    20. Делаем поддержку разных рецептов крафта, а так же фиксим разные баги у инвентаря.
    21. Создаем систему смены дня и ночи, а так же делаем новую сцену для нашего проекта.
    22. Начинаем создавать AI для агрессивных ботов.
    23. Делаем атаку мобов, а так же реакцию на атаку. Плюс реализуем сбор лута с мертвых мобов.
    24. Делаем зону спауна для нпц. Так же добавляем генерацию случайных предметов в инвентаре.
    25. Обновляемся до 4.13, а так же делаем дальних агрессивных нпц.
    26. Добавляем разные элементы на HUD. Добавляем ручную перезарядку оружия.
    27. Доделываем поддержку скелетной одежды и шапок. Добавляем анимацию для оружия от первого лица.
    28. Делаем интерфейс для работы с нашей системой экипировки.
    29. Начинаем делать торговую систему и компонент менеджмента денег.
    30. Продолжаем делать торговлю, создавая и настраивая компонент торговли.
    31. Делаем отмену торговли, а так же настраиваем анимацию перезарядки.
    32. Создаем транспорт со своим инвентарем, фарами и переключением вида. Создаем фонарик.
    33. Создаем строительство (а точнее систему размещения объектов перед собой).
    34. Делаем интерфейс для строительства, делаем привязку для стен.
    35. Создаем ещё несколько видов конструкций: Палатка, кровать, стул, стол, лампа, дверь. сундук, костер.
    36. Добавляем крышу, окна. Доделываем выравнивание относительно других конструкций.
    37. Делаем небольшое поселение, а так же населяем его NPC, которые так же создаем в этом уроке.
    38. Начинаем делать систему диалогов для наших жителей.
    39. Настраиваем туман и постобработку. Импортируем модель зомби и настраиваем ему анимации.
    40. Доделываем систему диалогов.
    41. Делаем взаимодействие с предметами от третьего лица, а так же модификаторы для брони.
    42. Создаем главное меню, меню паузы и настройки графики. А так же собираем первую сборку игры.
    43. Реализуем расписание для уникальных жителей.А так же что бы городские NPC убегали от атаки.
    44. Добавляем контекстное меню в инвентарь, а так же фиксим некоторые баги нашего инвентаря.
    45. Добавляем отдачу, разброс, анимацию выстрела и возможность ударить для огнестрельного оружия.
    46. Доделаем агрессивных и городских NPC, фиксим разные баги, связанные с ними.
    47. Настраиваем анимации для главного персонажа. Добавляем различную одежду.
    48. Исправляем различные ошибки в нашей игре.
    49. Исправляем различные ошибки крафта, NPC и экипировки в нашей игре.
    50. Немного дорабатываем карту и собираем последний билд.

    Чем же являются все эти каталоги и файлы?

    Также как и в Unity, проекты в Unreal обычно находятся в их собственной папке и имеют собственный файл проекта. Вы можете сделать двойной щелчок по .uproject файлу, чтобы загрузить вашу игру в Unreal Editor, или сделать щелчок правой кнопкой мыши для дополнительных опций. Внутри папок проекта существует несколько различных подкаталогов, которые содержат материалы и исходный код игры и, также, разные файлы конфигураций. Но самые важные подкаталоги это Content и Source .

    Куда я могу положить файлы материалов игры?

    В UE4, каждый проект имеет папку Content . Она чем-то похожа на папку Assets в Unity, там содержатся материалы к вашей игре. Чтобы добавить материал в игру, можно просто переместить файлы в папку Content проекта с которым вы работаете и они автоматически появятся в . Материалы в редакторе автоматически обновятся, как только вы сделаете какое-либо изменение в них при помощи каких-либо других программ.

    Какие файлы поддерживаются?

    Unity поддерживает огромное количество типов файлов, в то время как Unreal Engine 4 поддеждивает только самые распространенные типы файлов:

    Asset Type Supported Formats
    3D .fbx, .obj
    Texture .png, .jpeg, .bmp ,.tga, .dds, .exr, .psd, .hdr
    Sound .wav
    Fonts .ttf, .otf
    Videos .mov, .mp4, .wmv

    Как и куда сохраняется моя сцена?

    В Unity, вы располагаете GameObjects на сцене и сохраняете сцену как файл Scene. В Unreal же существует Map файл , чем-то напоминающим Unity Scene. Map файлы содержат данные о вашем Уровне и находящиеся объекты в нем, а также данные освещения особые настройки уровня.

    Как изменить настройки проекта?

    Перейти к настройкам проекта можно из главного меню, перейдя в Edit / Project Settings . Также, как и в Unity, в настройках можно изменить данные о проекте (такие как название проекта и иконки), изменить сочетания клавиш, и определить поведения движка во время запуска вашей игры. Узнать больше об индивидуальных настройках проекта можно . Unity также имеет то что обычно называется "настройками игрока". В Unreal, они называются "platform settings", и их можно изменить в категории "Platforms" на странице настроек проекта.

    Где мои исходники?

    В Unity, вы привыкли хранить исходники файлов C# в папке материалов игры.

    UE4 работает иначе. Для проектов, что используют код на C++, вы можете найти подкаталог "Source " внутри папки проекта, который имеет множество различных файлов в том числе и C++ исходные файлы (.cpp) и заголовочные (.h) файлы, а также некоторые файлы компиляции (.Build.cs, .Target.cs). Однако, проекты основанные только на блюпринтах не имеют папки Source.

    Самый простой способ начать использовать C++ в UE4 это использовать функцию редактора добавить код к проекту (Add Code to Project) (в главном файловом меню), или просто создать новый C++ проект с нуля, на основе одного или нескольких шаблонов. Вы можете найти C++ классы прямо в менеджере материалов (Content Browser) и открыть их в Visual Studio или Xcode двойным нажатием левой кнопки мыши на их иконках.

    От GameObjects к экторам

    Где же мой GameObject?

    В Unity, GameObject это нечто, что можно поместить на сцене. Эквивалентом этому в UE4 является эктор. В Unreal Editor вы можете переместить новый пустой (Empty) эктор в окно просмотра из панели размещения (Placement panel):

    Вы конечно же можете сделать игру из пустых экторов, но в UE4 есть также несколько специальных типов экторов с особыми настройками, например Точка начала (Pawn) (для игроков или ИИ объектов), или Персонаж (Character) (для анимированных созданий.) Также как и пустые экторы, вы можете переместить в окно обзора эти специальные типы экторов, а затем настроить их свойства или добавить необходимые компоненты. Вы узнаете об этом больше, но сейчас постарайте but for now try to remember that UE4 has a Gameplay Framework that works with these special Actors.

    Actors in UE4 are a bit different than GameObjects in Unity. In Unity, GameObject is C# class which you cannot directly extend. In UE4, Actor is a C++ class which you can extend and customize using inheritance. We will talk about this more later on!

    Where Are My Components?

    In Unity, you add components to a GameObject to give it functionality.

    In UE4, you add components to Actors. After you have dropped an Empty Actor in your level, click the Add Component button (in the Details panel) and choose a component to add. Here, we are creating a torch by dropping an empty Actor, then adding a mesh component for the base, followed by a light source and then a particle system to create its flame.

    In Unity, a GameObject hold a flat list of components, but in UE4 an Actor actually contains a hierarchy of components attached to one another. You can see this in the example above, where the Light and Particle are attached to the Mesh. This has some important implications discussed later in Complex Actors and GameObjects .

    From Unity prefabs to UE4 Blueprint Classes

    Unity"s workflow is based on prefabs. In Unity you build a set of GameObjects with components, then create a prefab from them. You can then place instances of the prefab in your world, or instantiate them at runtime.

    UE4"s corresponding workflow is based on Blueprint Classes. In UE4, you build an Actor with components, select it, and click the "Blueprint / Add Script " button (in the Details panel). Then, choose a place to save your Blueprint Class, and click "Create Blueprint " to save your new Blueprint Class!

    Your new Blueprint Classes can be found in the Content Browser . You can double-click to edit them directly, or you can drag and drop them into any level.

    Where is Script Component and MonoBehaviour?

    In Unity, you have Script Components that you drop on GameObjects to add C# scripting. You create a class that inherits from MonoBehaviour to define what that component does.

    UE4 has something similar. You can create whole new Component classes of your own and drop those onto any Actor. You can create Component classes using either Blueprint Scripting or C++.

    So how do you create your own component class in UE4? In the Details panel"s Add Component drop-down, you see you can create new components, or choose existing ones:

    In Unity, when creating a new MonoBehaviour, you will be given a skeleton class file with a Start() function and an Update() function.

    In UE4, you will also be given a skeleton class with a InitializeComponent() function and a TickComponent() function, which perform functions similar to Start and Update.

    If you create a Blueprint Script Component you will be given these same functions as visual nodes:

    Scriptable Actor Blueprint Classes

    Here is a cool feature in UE4: Your new Actor Blueprint Class can have its own Blueprint Visual Scripting! This allows you to add logic to an entire object, not only an individual component. Combined with inheritance (explained below), this gives you a lot of flexibility when designing your game.

    In addition to Blueprint Classes supporting visual scripting, UE4 also supports C++ Classes implemented with code. Here are both, side-by-side.

    Unity C# UE4 C++
    using UnityEngine ; using System . Collections ; public class MyComponent : MonoBehaviour { int Count ; // Use this for initialization. void Start () { Count = 0 ; } // Update is called once per frame. void Update () { Count = Count + 1 ; Debug . Log (Count ); } } #pragma once #include "GameFramework/Actor.h" #include "MyActor.generated.h" UCLASS () class AMyActor : public AActor { GENERATED_BODY () int Count ; // Sets default values for this actor"s properties. AMyActor () { // Allows Tick() to be called PrimaryActorTick . bCanEverTick = true ; } // Called when the game starts or when spawned. void BeginPlay () { Super :: BeginPlay (); Count = 0 ; } // Called every frame. void Tick (float DeltaSeconds ) { Super :: Tick (DeltaSeconds ); Count = Count + 1 ; GLog -> Log (FString :: FromInt (Count )); } };
    UE4 Blueprint

    UE4 Blueprint Classes can be extended

    Unity prefabs and UE4 Blueprint Classes can be instantiated in your game similarly. However, Unity has complications related to nesting prefabs within other prefabs, which limit their role as extensible building blocks.

    In UE4, you can create a new Blueprint Class which extends an existing Blueprint Class and augments it with new properties, components, and visual scripting functionality.

    For example, in UE4 you can create a Blueprint Class named Monster which implements basic monster functionality such as chasing people. You can then create further Blueprint Classes which extend it, such as Dragon (a type of Monster which adds fire-breathing features), Grue (a Monster which is likely to eat you when it is dark), and for example 8 others. These subclasses of Monster all inherit the basic functionality from Monster, and add new capabilities on top.

    In Unity, you would implement this by creating many different GameObject prefabs: one for Dragon, one for Grue, and so on. Now, say you want to add some new functionality to all monsters, such as the ability to speak using your new Speak Component. In Unity, you have to go and update all 10 prefabs to individually copy and paste the new functionality into it.

    In UE4, you can simply modify the Monster Blueprint Class to add this new ability to speak. That"s all! Dragon, Grue, and the 8 other subclasses of Monster automatically inherit the new speaking functionality, and you do not need to touch them.

    But there is more! Everything we have said here about Blueprint Classes also applies to C++ Classes, and everything is equally true of Actors and Components. These systems are designed to support large-scale development of extensible functionality, and can scale to projects with 10"s or 100"s of developers.

    Should I use Blueprint Scripting, C++, or both?

    Blueprint Visual Scripting is ideal for simple in-game logic flow and sequencing of actions. It is a great system for designers, artists, and visually-oriented programmers, because it is easy to access and control in-game objects visually. You can even create small standalone-game using just Blueprints; see the Tappy Chicken sample for a full-fledged example.

    C++ programming is for larger-scale tasks, such as building gameplay systems, complex AI, and new engine features. If you already have some C++ experience, check out the Introduction to C++ Programming in UE4 page.

    Most projects will use a mix of Blueprints and C++. Many developers prototype game functionality using Blueprints, because it is so easy and fun, and later move some or all of it to C++ for performance and engineering rigor.

    Blueprint Classes can extend C++ Classes

    Much of the magic of UE4 game development comes from the interplay between programmers implementing new features in C++, with designers and artists utilizing them in Blueprints and then asking for more! Here"s how a team might structure a UE4-based shooter game implementing pickups using a mix of C++ Classes systems programming, and Blueprint Classes for behavior and appearance:

    Transform Components

    In Unity each GameObject has a Transform component, which gives the GameObject a position, rotation, and scale in the world.

    Similarly in UE4, Actors have a Root Component , which can be any subclass of Scene Component. A Scene Component gives the Actor a location, rotation, and scale in the world which is applied hierarchically to all components underneath it. Many of the components that you will use are subclassed from Scene Component, because it is really useful to have a position!

    Even if you place an Empty Actor, UE4 will create a "Default Scene Root" for that Actor, which is just a plain Scene Component. If you drop a new Scene component in of your own, it will replace the Default Scene Root.

    Compound Objects

    In Unity, you create compound objects by constructing a hierarchy of GameObjects and parenting their transforms together:

    In UE4, you create compound game objects by nesting components hierarchically:

    As you can see from the diagram, nested hierarchies can be created by attaching Scene Components to one another, since they have a transform - similar to parenting transforms in Unity. Actor Components (the base-class for all components) can only be attached directly to the Actor itself.

    Do I build everything out of Components?

    Its really up to you, but most often you will use a combination of custom component types along with Actor classes that use those components. We mentioned this earlier, but UE4 has many special types of Actors that guarantee a certain level of capability and always include certain components. For example, a Character always contains a Character Movement Component .

    There are several sub-classed Actor types you will quickly encounter in the engine and are useful in almost every type of game. Here is a list of our most common built-in Actors:

      Pawn - A type of Actor representing a controllable game object, typically the player"s avatar. Pawns are moved by Players and AI alike through an owning Controller.

      Character - A more specialized version of Pawn designed for biped avatars that handle a lot of the complexity of those kinds of game objects.

      Controller - Possesses and controls a Pawn. By separating the Pawn from the controller, you can write AI Controllers that can manipulate a pawn using the same interface the player would.

      Player Controller - A more specialized Controller designed for getting input from a player"s Gamepad, Touch, or Mouse/Keyboard, and using that input to drive the Pawn or Character they possess.

    So is everything an Actor?

    Not everything. Actors are most common class used for gameplay in UE4 and the only type that can be Spawned into the World . So everything you place in your level will be an Actor.

    The other important type to know about is Object . Object is actually the base class of all Unreal classes, including Actor and many others. This is a much lower-level construct than Actor, but still has features that you will expect from a Unreal class, such as reflection and serialization . Object is a very basic class we use when we need to define a new type that just does not fit the mold of an Actor . For example, Actor Component is the base class for all Components, and derives from Object instead of Actor .

    What is this Gameplay Framework thing in UE4?

    Okay, so this is where things get a little crazy (in sort of an awesome way.) Unity gives you a clean slate to start designing your game, and Unreal does the same. In Unity you can build everything out of basic GameObjects and components, and in Unreal you can build everything out of Actors and components.

    However Unreal has this extra layer on top called the Gameplay Framework . This does not really exist in Unity at all. You do not have to use it in Unreal, but it is actually super cool! Basically, if you make use of some basic primitive classes and follow certain established conventions, your game will acquire some awesome features automatically that would be otherwise very difficult to implement or retrofit (such as full multiplayer support!)

    Countless awesome games have been designed on top of Unreal"s Gameplay Framework, and it is worth taking some time to understand how it works. Yes, you could roll your own version of this. That is totally fine if you want to! But hundreds of awesome Unreal developers have made great use of this framework in UE4 today, so it is worth taking some time to learn.

    To use the Gameplay Framework, you really just need to learn the customized built-in Actor classes included with Unreal, such as Pawn , Character , and Player Controller , and eventually learn about how Unreal replication and networking features work. For now, let us get back to the basics though.

    How to write code in UE4

    So, I"m used to programming in MonoDevelop

    For Blueprint scripting, you will only need Unreal Editor -- everything is built in! To write code in C++, download the free version of Visual Studio on Windows, or install Xcode on Mac. When you first create a new project (or add code to an existing project), UE4 will automatically create Visual Studio project files for you. You can open Visual Studio by double-clicking on a C++ class inside Content Browser , or by clicking the "Open Visual Studio" button in the main File menu.

    One important difference in UE4: You will sometimes have to manually refresh your Visual Studio project files (for example, after downloading a new version of UE4, or when manually making changes to source file locations on disk.) You can do this by clicking "Refresh Visual Studio Project" in the main menu, or by right-clicking on the .uproject file in your project"s directory and selecting "Generate Visual Studio project files"

    Writing Event Functions (Start, Update, etc.)

    If you are used to working with MonoBehaviors you are used to such methods as Start, Update, and OnDestroy. Here is a comparison between a Unity behavior and its counterpart in UE4 Actors and components.

    In Unity, we might have a simple component that looks like this:

    public class MyComponent : MonoBehaviour { void Start () {} void OnDestroy () {} void Update () {} }

    But remember, in UE4 you can write code right on the Actor itself rather than only coding new component types. This is actually very common and useful.

    Similar to Unity"s Start, OnDestroy, and Update functions, we have a similar set of methods for Actors in UE4:

    UCLASS () class AMyActor : public AActor { GENERATED_BODY () // Called at start of game. void BeginPlay (); // Called when destroyed. void EndPlay (const EEndPlayReason :: Type EndPlayReason ); // Called every frame to update this actor. void Tick (float DeltaSeconds ); };

    Blueprint :

    Components in UE4 contain different functions. Here is a simple example:

    UCLASS () class UMyComponent : public UActorComponent { GENERATED_BODY () // Called after the owning Actor was created void InitializeComponent (); // Called when the component or the owning Actor is being destroyed void UninitializeComponent (); // Component version of Tick void TickComponent (float DeltaTime , enum ELevelTick TickType , FActorComponentTickFunction * ThisTickFunction ); };

    Blueprint :

    Remember, in UE4 it is important to call the parent class" version of method.

    For example, in Unity C# this would be called base.Update(), but in UE4 C++ we will use Super::TickComponent():

    void UMyComponent :: TickComponent (float DeltaTime , enum ELevelTick TickType , FActorComponentTickFunction * ThisTickFunction ) { // Custom tick stuff here Super :: TickComponent (DeltaTime , TickType , ThisTickFunction ); }

    You may have noticed some things begin with "A" and others with "U" in C++. The prefix "A" indicates an Actor sub-class. Where as the prefix "U" indicates an Object sub-class. There are some other prefixes too, for example "F" is used for most plain data structures or non-UObject classes.

    Writing gameplay code in UE4

    Okay, things are going to get a bit deeper from here on out. We will be talking about programming topics that are critical for creating games. Because you know Unity, we will be explaining features with slant toward C# users learning Unreal C++, but you can use Blueprint Scripting for pretty much everything if you want! We have added examples in both C++ and Blueprint where possible.

    Let us talk about some of the most common gameplay programming patterns and how you would approach them in Unreal. Many functions in Unity have a comparable function in Unreal that should seem familiar. We will go through the most common functions one by one.

    Instantiating GameObject / Spawning Actor

    In Unity, we use the Instantiate function to create new instances of objects.

    This function takes any UnityEngine.Object type (GameObject, MonoBehaviour, etc.), and makes a copy of it.

    public GameObject EnemyPrefab ; public Vector3 SpawnPosition ; public Quaternion SpawnRotation ; void Start () { GameObject NewGO = (GameObject ) Instantiate (EnemyPrefab , SpawnPosition , SpawnRotation ); NewGO . name = "MyNewGameObject" ; }

    In UE4, there are a couple different functions to instantiate objects, depending on your needs. NewObject is used for creating new UObject types, and SpawnActor is used for spawning AActor types.

    First we will briefly talk about UObjects and NewObject. Subclassing UObject in Unreal is much like subclassing ScriptableObject in Unity. They are useful for gameplay classes that do not need to spawn into the world or have attached components like Actors do.

    In Unity, if you created your own subclass of ScriptableObject, you may instantiate it like this:

    MyScriptableObject NewSO = ScriptableObject . CreateInstance < MyScriptableObject >();

    And in Unreal, if you created your own UObject derived type, you may instantiate it like this:

    UMyObject * NewObj = NewObject < UMyObject >();

    So what about Actors? Actors are spawned using the SpawnActor method on a World (UWorld in C++) object. How do you get the World object? Some UObjects provide a GetWorld method for you, as an example, all Actors do.

    You will notice instead of passing in another Actor, we pass in the "class" of the Actor we want to spawn. In our example, the class can be any subclass of AMyEnemy.

    But what if you want to make a "copy" of another object, like what Instantiate allows you to do?

    The NewObject and SpawnActor functions can also be given a "template" object to work with. Unreal will make a copy of that object, instead of making one "from scratch". This will copy over all of its UPROPERTYs and components.

    AMyActor * CreateCloneOfMyActor (AMyActor * ExistingActor , FVector SpawnLocation , FRotator SpawnRotation ) { UWorld * World = ExistingActor -> GetWorld (); FActorSpawnParameters SpawnParams ; SpawnParams . Template = ExistingActor ; World -> SpawnActor < AMyActor >(ExistingActor -> GetClass (), SpawnLocation , SpawnRotation , SpawnParams ); }

    You might be wondering what "from scratch" means in this context. Each object class you create has a default template that contain default values for its properties and components. If you do not override these properties and do not provide your own template, Unreal will use these default values to construct your object. To help illustrate this, let us first look at a MonoBehaviour for example:

    public class MyComponent : MonoBehaviour { public int MyIntProp = 42 ; public SphereCollider MyCollisionComp = null ; void Start () { // Create the collision component if we don"t already have one if (MyCollisionComp == null ) { MyCollisionComp = gameObject . AddComponent < SphereCollider >(); MyCollisionComp . center = Vector3 . zero ; MyCollisionComp . radius = 20.0f ; } } }

    In the above example, we have an int property that defaults to 42, and a SphereCollider component that defaults to a radius of 20.

    We can achieve the same thing in Unreal using the object"s constructor.

    UCLASS () class AMyActor : public AActor { GENERATED_BODY () UPROPERTY () int32 MyIntProp ; UPROPERTY () USphereComponent * MyCollisionComp ; AMyActor () { MyIntProp = 42 ; MyCollisionComp = CreateDefaultSubobject < USphereComponent >(FName (TEXT ("CollisionComponent" )); MyCollisionComp -> RelativeLocation = FVector :: ZeroVector ; MyCollisionComp -> SphereRadius = 20.0f ; } };

    In the constructor of AMyActor, we have set the default property values for the class. Note the use of the CreateDefaultSubobject function. We can use it to create components and assign default properties to them. All the subobjects we create using this function act as a default template, so we can modify them in a subclass or Blueprint.

    Casting from one Type to Another

    In this case, we get a component we know we have, then cast it to a specific type and conditionally do something.

    Collider collider = gameObject . GetComponent < Collider >; SphereCollider sphereCollider = collider as SphereCollider ; if (sphereCollider != null ) { // ... } UPrimitiveComponent * Primitive = MyActor -> GetComponentByClass (UPrimitiveComponent :: StaticClass ()); USphereComponent * SphereCollider = Cast < USphereComponent >(Primitive ); if (SphereCollider != nullptr ) { // ... }

    Destroying GameObject / Actor

    Unity C++ Blueprint
    Destroy (MyGameObject ); MyActor -> Destroy ();

    Destroying GameObject / Actor (With 1 Second Delay)

    Unity C++ Blueprint
    Destroy (MyGameObject , 1 ); MyActor -> SetLifeSpan (1 );

    Click for full view.

    Disabling GameObjects / Actors

    Unity C++ Blueprint
    MyGameObject . SetActive (false ); // Hides visible components MyActor -> SetActorHiddenInGame (true ); // Disables collision components MyActor -> SetActorEnableCollision (false ); // Stops the Actor from ticking MyActor -> SetActorTickEnabled (false );

    Click for full view.

    Accessing the GameObject / Actor from Component

    Unity C++ Blueprint
    GameObject ParentGO = MyComponent . gameObject ; AActor * ParentActor = MyComponent -> GetOwner ();

    Click for full view.

    Accessing a Component from the GameObject / Actor

    MyComponent MyComp = gameObject . GetComponent < MyComponent >(); UMyComponent * MyComp = MyActor -> FindComponentByClass < UMyComponent >();

    Blueprint

    Finding GameObjects / Actors

    // Find GameObject by name GameObject MyGO = GameObject . Find ("MyNamedGameObject" ); // Find Objects by type MyComponent Components = Object . FindObjectsOfType (typeof (MyComponent )) as MyComponent ; foreach (MyComponent Component in Components ) { // ... } // Find GameObjects by tag GameObject GameObjects = GameObject . FindGameObjectsWithTag ("MyTag" ); foreach (GameObject GO in GameObjects ) { // ... } // Find Actor by name (also works on UObjects) AActor * MyActor = FindObject < AActor >(nullptr , TEXT ("MyNamedActor" )); // Find Actors by type (needs a UWorld object) for (TActorIterator < AMyActor > It (GetWorld ()); It ; ++ It ) { AMyActor * MyActor = * It ; // ... }

    // Find UObjects by type for (TObjectIterator < UMyObject > It ; It ; ++ it ) { UMyObject * MyObject = * It ; // ... } // Find Actors by tag (also works on ActorComponents, use TObjectIterator instead) for (TActorIterator < AActor > It (GetWorld ()); It ; ++ It ) { AActor * Actor = * It ; if (Actor -> ActorHasTag (FName (TEXT ("Mytag" )))) { // ... } }

    Adding tags to GameObjects / Actors

    MyGameObject . tag = "MyTag" ; // Actors can have multiple tags MyActor . Tags . AddUnique (TEXT ("MyTag" ));

    Adding tags to MonoBehaviours / ActorComponents

    // This changes the tag on the GameObject it is attached to MyComponent . tag = "MyTag" ; // Components have their own array of tags MyComponent . ComponentTags . AddUnique (TEXT ("MyTag" ));

    Comparing tags on GameObjects / Actors and MonoBehaviours / ActorComponents

    if (MyGameObject . CompareTag ("MyTag" )) { // ... } // Checks the tag on the GameObject it is attached to if (MyComponent . CompareTag ("MyTag" )) { // ... } // Checks if an Actor has this tag if (MyActor -> ActorHasTag (FName (TEXT ("MyTag" )))) { // ... }

    // Checks if an ActorComponent has this tag if (MyComponent -> ComponentHasTag (FName (TEXT ("MyTag" )))) { // ... }

    Physics: RigidBody vs. Primitive Component

    In Unity to give any GameObject physics characteristics, you first give it a RigidBody component. In Unreal, any PrimitiveComponent (UPrimitiveComponent in C++) can be a physical object. Some common Primitive Components are ShapeComponents (Capsule, Sphere, Box), StaticMeshComponent, and SkeletalMeshComponent.

    Unlike Unity which separates the responsibilities of collision and visualizations into separate components. Unreal combines the concepts of the potentially physical and the potentially visible into PrimitiveComponent. Any component that would have any geometry in the world, that could either be rendered or interacted with physically sub-classes from PrimitiveComponent.

    Layers vs Channels

    In Unity, they are called "Layers". UE4 uses Collision Channels, and they work in a similar way. You can read up on them .

    RayCast vs RayTrace

    GameObject FindGOCameraIsLookingAt () { Vector3 Start = Camera . main . transform . position ; Vector3 Direction = Camera . main . transform . forward ; float Distance = 100.0f ; int LayerBitMask = 1 << LayerMask . NameToLayer ("Pawn" ); RaycastHit Hit ; bool bHit = Physics . Raycast (Start , Direction , out Hit , Distance , LayerBitMask ); if (bHit ) { return Hit . collider . gameObject ; } return null ; } APawn * AMyPlayerController :: FindPawnCameraIsLookingAt () { // You can use this to customize various properties about the trace FCollisionQueryParams Params ; // Ignore the player"s pawn Params . AddIgnoredActor (GetPawn ()); // The hit result gets populated by the line trace FHitResult Hit ; // Raycast out from the camera, only collide with pawns (they are on the ECC_Pawn collision channel) FVector Start = PlayerCameraManager -> GetCameraLocation (); FVector End = Start + (PlayerCameraManager -> GetCameraRotation (). Vector () * 1000.0f ); bool bHit = GetWorld ()-> LineTraceSingle (Hit , Start , End , ECC_Pawn , Params ); if (bHit ) { // Hit.Actor contains a weak pointer to the Actor that the trace hit return Cast < APawn >(Hit . Actor . Get ()); } return nullptr ; }

    Click for full view.

    Triggers

    public class MyComponent : MonoBehaviour { void Start () { collider . isTrigger = true ; } void OnTriggerEnter (Collider Other ) { // ... } void OnTriggerExit (Collider Other ) { // ... } } UCLASS () class AMyActor : public AActor { GENERATED_BODY () // My trigger component UPROPERTY () UPrimitiveComponent * Trigger ; AMyActor () { Trigger = CreateDefaultSubobject < USphereComponent >(TEXT ("TriggerCollider" )); // Both colliders need to have this set to true for events to fire Trigger . bGenerateOverlapEvents = true ; // Set the collision mode for the collider // This mode will only enable the collider for raycasts, sweeps, and overlaps Trigger . SetCollisionEnabled (ECollisionEnabled :: QueryOnly ); } void BeginPlay () { // Register to find out when an overlap occurs OnActorBeginOverlap . AddDynamic (this , & AMyActor :: OnTriggerEnter ); OnActorEndOverlap . AddDynamic (this , & AMyActor :: OnTriggerExit ); Super :: BeginPlay (); } void EndPlay (const EEndPlayReason :: Type EndPlayReason ) { OnActorBeginOverlap . RemoveDynamic (this , & AMyActor :: OnTriggerEnter ); OnActorEndOverlap . RemoveDynamic (this , & AMyActor :: OnTriggerExit ); Super : EndPlay (EndPlayReason ); } UFUNCTION () void OnTriggerEnter (AActor * Other ); UFUNCTION () void OnTriggerExit (AActor * Other ); };

    You can read more about setting up collision responses .

    Kinematic Rigidbodies

    public class MyComponent : MonoBehaviour { void Start () { rigidbody . isKinimatic = true ; rigidbody . velocity = transform . forward * 10.0f ; } }

    In UE4, The collision component and rigidbody component are one. The base class for this is UPrimitiveComponent, which has many subclasses (USphereComponent, UCapsuleComponent, etc.) to suit your needs.

    UCLASS () class AMyActor : public AActor { GENERATED_BODY () UPROPERTY () UPrimitiveComponent * PhysicalComp ; AMyActor () { PhysicalComp = CreateDefaultSubobject < USphereComponent >(TEXT ("CollisionAndPhysics" )); PhysicalComp -> SetSimulatePhysics (false ); PhysicalComp -> SetPhysicsLinearVelocity (GetActorRotation (). Vector () * 100.0f ); } };

    Input events

    public class MyPlayerController : MonoBehaviour { void Update () { if (Input . GetButtonDown ("Fire" )) { // ... } float Horiz = Input . GetAxis ("Horizontal" ); float Vert = Input . GetAxis ("Vertical" ); // ... } } UCLASS () class AMyPlayerController : public APlayerController { GENERATED_BODY () void SetupInputComponent () { Super :: SetupInputComponent (); InputComponent -> BindAction ("Fire" , IE_Pressed , this , & AMyPlayerController :: HandleFireInputEvent ); InputComponent -> BindAxis ("Horizontal" , this , & AMyPlayerController :: ); InputComponent -> BindAxis ("Vertical" , this , & AMyPlayerController :: HandleVerticalAxisInputEvent ); } void HandleFireInputEvent (); void HandleHorizontalAxisInputEvent (float Value ); void HandleVerticalAxisInputEvent (float Value ); };

    This is what your input properties in your Project Settings might look like:

    FAQ

    How do I load my last project automatically?

    If you are used to Unity automatically loading the last project you were working on, the same is possible in UE4. To enable, check "Always load last project on Startup" when opening a project. You can also toggle the setting at any time from the main Edit menu under Edit/Editor Preferences/Loading and Saving/Startup.

    Where do I set Input Bindings for my game?

    In Unity, you are used to using the Input Manager settings for Project to setup default bindings. In UE4 it works similarly. You will open your Project Settings then select the Input category. There, you can add various buttons (actions) and analog controls (axes). Give each control a name and default binding. Then, you can get callbacks to your game"s Pawn when the input events are triggered. Check out the Input documentation page for the details.

    How do I change the starting scene of my project?

    You can change the startup map of your project from the project settings tab. From the main menu choose Edit/Project Settings->Maps & Modes to change the starting map.

    How do I run my game?

    The easiest way to run your game is to click the "Play" button on the the main editor toolbar, which will run the game right inside the editor"s process. If you want to run it as a standalone application, click the dropdown arrow next to "Play" and choose "Standalone Game". Finally, if you want to run on a mobile device or in a web browser, you will use the "Launch" button on the toolbar (after installing any prerequisites that are needed for that platform.)

    What units are these?

    In Unity, the primary unit of measurement is one meter. In UE4, the primary unit of measurement is one centimeter.

    So if you move something 1 unit (meter) in unity that is equivalent to moving something 100 units (centimeters) in UE4.

    If you want to move something 2 Feet in Unity that would be 0.61units (meter) and in UE4 is 61 units (centimeters).

    What is with this coordinate system? Which way is up?

    Both Unity and UE4 use a left-handed coordinate system, but the axes are swapped around. In UE4, positive X is "forward", positive Y is "right" and positive Z is "up". This cannot be changed, so you will have to get used to it.

    How do I see Log Output from my game?

    In the UE4 editor, you can open the "Output Log" from the "Window -> Developer Tools" menu. You can also run your game with the "-log" command-line parameter to summon a dedicated log window alongside your game, which is really useful!

    Speaking of Log Output, where is my Debug.Log?

    Logging in UE4 is highly customizable. Read up on how to log messages .

    How do I throw exceptions?

    In Unity, you are used to throwing exceptions when things go wrong. UE4 does not use exception handling. Instead, use the "check()" function to trigger a critical assertion error. You can pass in an error message. If you want to report an error but not halt the program, use "ensure()" instead. This will log an error with a full call stack, but program execution will continue. If you had a debugger attached, both functions will break into the debugger.

    Where is the .NET Framework?

    Unlike Unity, UE4 does not use the .NET framework. UE4 has its own set of container classes and libraries. Common container comparisons:

    .Net Framework UE4
    String FString , FText
    List TArray
    Dictionary TMap
    HashSet TSet

    Does Unreal automatically reload code changes?

    Yes! You can leave the editor open while you write code. Simply kick off a compile from Visual Studio after you have finished editing code, and the editor will "hot reload" your changes automatically. You can also click the Compile button on the editor"s main toolbar. That can be useful when you have the Visual Studio debugger attached.

    Where to go from here

    Thanks for reading the guide! This was created for the Unreal community with the help of Unreal developers everywhere, and we very much appreciate any feedback and corrections you can offer. We will try to keep improving this document as we learn more about what is most helpful when transitioning to UE4!

    We have many additional UE4 learning resources available!

    Please enable JavaScript to view the Мы уже сообщали, что компания Epic Games в прошлом месяце выпустила версию 4.7 своего высокотехнологичного игрового движка , в которой было сделано огромное количество нововведений, доработок, улучшений и исправлений найденных багов прошлой версии. В частности, в ней был улучшен функционал для реализации открытых миров, повышена реалистичность листвы, а также доработано внедрение Blueprint для ещё большего упрощения прототипирования геймплея и мн.др.

    Если вы пропустили события, связанные с движком и представленные на GDC 2015 , то о многом не узнали. В частности, именно на ней было объявлено о нынешней бесплатности UE4 (со 2 марта), была показана реалтаймовая демонстрация с открытым миром «Kite », был показан «Thief in the Shadows » для VR в сотрудничестве с Weta Digital , был открыт исходный код физического движка от NVIDIA специально для пользователей UE4 и мн.др.

    Также был усовершенствован Marketplace , на котором вы теперь можете просматривать предлагаемые инструменты и ресурсы без запуска лаунчера, прямо через браузер. Кстати, все подписчики движка после его перехода в открытый доступ, получили деньги на счёт для последующей траты в данном магазине.

    Но щедрость Epic Games на этом не закончилась, и она продолжила искать перспективные проекты пользователей, предоставляя разработчикам оных денежные средства из специального фонда Unreal Dev Grants , который она для этого ранее организовала, наполнив его банк на 5000000 $. Об этом мы также рассказывали на страницах сайт . Но сегодня хотелось бы обратить ваше внимание на несколько таких проектов, получивших денежные поощрения от Epic Games .

    Из новых проектов на UE4 можно отметить работы французского художника Koola , который занимается реализацией фотореалистичных сцен, попутно делясь своими работами и помогая другим пользователям на официальном форуме движка. Вы можете глянуть видеоролики на его канале в сервисе YouTube . Этот разработчик получил грант на 18000 $.

    Jake Kaufman и Jessie Seely на сервисе Kickstarter запустили кампанию по сбору средств для реализации их проекта « The New Renaissance » на базе UE4 , и собрали нужные 70000 $. Это будет первая рок-опера в виртуальной реальности. Также данный проект получил грант от Epic Games в размере 18000 $.

    А разработчик Mike Blackney делает horror-игру «Grand Theft Cthulhu », которую он стилизует под комиксы 80-ых годов. Игру он делает в одиночку, кое в чём прибегая к помощи друзей. Компания Epic Games предоставила разработчику этого проекта грант в размере 15000 $. Вы можете посмотреть видео об игре на YouTube .

    Три выпускника колледжа из Германии реализовывают архитектурный проект «Consight » для iPad . Их проект получил 15000 $ в качестве поддержки в рамках Unreal Dev Grant . Узнать подробности о их разработке вы можете .

    А команда Magic and Mirrors , состоящая из Kevin Bryant , Kevin Greenlee и Michelle Morger , работает над игрой «Nelo ». Это экшен от третьего лица с быстрыми боями и впечатляющей визуализацией. Этот проект показывался в рамках стенда Unreal Engine на прошедшей выставке GDC . Студия получила грант в размере 20000 $. Вы можете посетить официальный сайт , чтобы узнать подробности.

    Разработчик-одиночка Adrian Lazar из Бразилии уже в течение 9 месяцев работает над проектом «Planet Alpha 31 ». Эту игру Epic Games также показывала на прошедшей выставке GDC 2015 , предоставив её разработчику денежный грант в размере 15000 $. Узнать подробности об игре вы можете на её официальном сайте .

    Кстати, уважаемые игроделы сайт , если у вас имеется качественный проект, разрабатываемый вами на UE4 , то вы можете рассчитывать на подобное вознаграждение (от 5000 до 50000 $), если обратитесь к Epic Games по контактным данным, предоставленным на данной странице.

    Не теряйте время! Получив деньги, вы сможете меньше волноваться о разработке, уделяя больше внимания проекту, не отвлекаясь на бытовые вопросы. Тем более, что для РФ данные суммы достаточно весомы и часто удовлетворяют полностью все затраты на производство игры.



    
    Top