Если вы пропустили события, связанные с движком и представленные на 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 по контактным данным, предоставленным на данной странице.
Не теряйте время! Получив деньги, вы сможете меньше волноваться о разработке, уделяя больше внимания проекту, не отвлекаясь на бытовые вопросы. Тем более, что для РФ данные суммы достаточно весомы и часто удовлетворяют полностью все затраты на производство игры.
Также как и в 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 двойным нажатием левой кнопки мыши на их иконках.
В 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!
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 .
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.
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:
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 |
---|
|
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.
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.
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:
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.
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.
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.
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 .
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.
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"
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.
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.
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.
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 ) { // ... }Unity | C++ | Blueprint |
---|---|---|
Destroy (MyGameObject ); | MyActor -> Destroy (); |
Unity | C++ | Blueprint |
---|---|---|
Destroy (MyGameObject , 1 ); | MyActor -> SetLifeSpan (1 ); |
Click for full view. |
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. |
Unity | C++ | Blueprint |
---|---|---|
GameObject ParentGO = MyComponent . gameObject ; | AActor * ParentActor = MyComponent -> GetOwner (); |
Click for full view. |
Blueprint
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.
In Unity, they are called "Layers". UE4 uses Collision Channels, and they work in a similar way. You can read up on them .
Click for full view.
You can read more about setting up collision responses .
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 ); } };This is what your input properties in your Project Settings might look like:
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.
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.
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.
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.)
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).
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.
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!
Logging in UE4 is highly customizable. Read up on how to log messages .
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.
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 |
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.
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Приветствую, Хабр! Хотел бы познакомить вас с относительно небольшим проектом, который я сделал c нуля примерно за 150 часов (50 заходов ~3 часа каждый) на Unreal Engine 4. Проект я делал в прямом эфире только на стримах раз в неделю (в общей сложности ушел год), попутно отвечая на вопросы пользователей.
Сам проект не предназначался как коммерческий. Целью я ставил на практике показать всю сложность разработки игр, а именно такие проблемы, как:
В конце всей серии стримов у нас получился играбельный прототип “Сурвайвл” шутера. Те, у кого стакан наполовину полон, смогут даже назвать это пре-альфой без сюжета.
Если вам интересны подробности проекта, записи стримов, исходники и прочее, читайте далее.
Весь проект был реализован на визуальной системе программирования, под названием “Блупринты”. И конечно многие спецы могут назвать её ребяческой, разработать на ней можно спокойно даже относительно крупный проект. Более того, это можно сделать относительно быстро, как мы уже смогли доказать.
Сразу хочу ответить на вопрос: "Почему Блупринты, а не С++? ". Ну во первых, когда я начинал серию, плюсы я почти не знал. Хотя я и сейчас подобный сингл делал бы на БП. Во вторых, БП почти не уступают плюсам в нашем случае, но при этом дают ряд возможностей: Не позволяют наделать множество ошибок, возможных с плюсами, не приходится отвлекаться между БП и С++, понятнее новичкам. Да и они в нашем случае не намного медленнее, учитывая тот факт, что почти вся логика построена на событиях.
Мы так же успели немного поработать над графикой. К сожалению, ассеты делать времени у нас не было, поэтому мы часть оставили пустышками, часть сделали прямо в редакторе из примитивов, а некоторый контент позаимствовали из бесплатных демок Epic Games. Тем не менее, что-то успели сделать и сами, например систему дня и ночи, постобработку для воды и некоторые материалы объектов сцены.
В планы моих стримов так же стояли и проблемы, которые могут возникнуть при разработке. Их я специально решал в прямом эфире, дабы не только показать, с чем могут столкнуться юные разработчики, но и как отлаживать свой код, искать баги и писать свой код так, что бы все это дело можно было делать в два раза быстрее. Конечно опыта в программировании у меня не десятки лет, и это сказывалось на том, какие порой глупые ошибки я делал. Да и уверен, что многие разработчики могут оспорить множество моментов в процессе написания игры.
Естественно, полноценной игрой это вряд ли можно назвать, так как нету ни сюжета, ни цели в игре - только чистая механика. Тем не менее, я считаю, что результатом можно гордится и он вполне отражает то, для чего задумывался весь проект.
Список всего, что мы успели реализовать в нашей игре
Персонаж
Объектная система инвентаря
Система экипировки
Содержание по частям