SlideShare uma empresa Scribd logo
1 de 34
Baixar para ler offline
Unreal Engine Basics
Chapter 3: Gameplay
Nick Prühs
Objectives
• Learning how to expose class fields and functions to blueprints
• Writing basic Unreal gameplay code, such as spawning actors,
accessing components and listening for events
• Getting familiar with gameplay concepts in the context of Unreal, such
as damage and collision
UPROPERTY
• For the Unreal reflection system to be able to discover C++ fields, we
need to annotate them with the UPROPERTY macro
 This is required for the garbage collector to observe these properties.
Forgetting to annotate a field of type UObject (or subtypes) can
result in crashes when trying to access that field!
 We can specify the behavior of the Unreal Editor with respect to
these fields by adding additional specifiers as parameters to that
macro.
/** Class of the projectile to fire. */
UPROPERTY(EditDefaultsOnly)
TSubclassOf<AActor> ProjectileClass;
UPROPERTY – Accessibility Specifiers
Specifier Description
VisibleDefaultsOnly Only visible in property windows for archetypes, and cannot be
edited.
VisibleInstanceOnly Only visible in property windows for instances, not for
archetypes, and cannot be edited.
VisibleAnywhere Visible in all property windows, but cannot be edited.
EditDefaultsOnly Can be edited by property windows, but only on archetypes.
EditInstanceOnly Can be edited by property windows, but only on instances, not
on archetypes.
EditAnywhere Can be edited by property windows, on archetypes and
instances.
UPROPERTY – Accessibility & Other Specifiers
Specifier Description
BlueprintReadOnly Can be read by Blueprints, but not modified.
BlueprintReadWrite Can be read or written from a Blueprint.
Category Category of the property when displayed in Blueprint editing
tools.
Config Value can be saved to the .ini file associated with the class and
will be loaded when created.
Replicated Replicated over the network.
ReplicatedUsing=
FunctionName
Replicated over the network, with a callback function which is
executed when the property is updated. Must be a UFUNCTION
(see later).
Class References
• Class references in Unreal are represented by pointers to UClass objects
(similar to Type references in Java or C#)
• To enforce compile-time type safety, you can use the template class
TSubclassOf
 The implementation of that template class will force you to include the
header of the referenced type – a forward declaration won’t be enough and
can lead to strange errors.
 This will automatically cause Unreal Editor windows to filter dropdowns for
selecting a class.
/** Class of the projectile to fire. */
UPROPERTY(EditDefaultsOnly)
TSubclassOf<AActor> ProjectileClass;
UCLASS Specifiers
Specifier Description
Abstract Prevents the user from adding Actors of this class to Levels.
Blueprintable Acceptable base class for creating Blueprints.
NotBlueprintable Not an acceptable base class for creating Blueprints. (Default)
BlueprintType Type that can be used for variables in Blueprints.
Config Allowed to store data in a configuration file (.ini).
Classes can be annotated with UCLASS, another Unreal Engine macro:
UCLASS Specifiers
Specifier Description
BlueprintSpawnableCom
ponent
Component class can be spawned by a Blueprint.
DisplayName Name of this node in a Blueprint.
Another UCLASS specifier provides additional options:
/** Adds a weapon to the actor, that fires projectiles. */
UCLASS(meta = (BlueprintSpawnableComponent))
class AWESOMESHOOTER_API UASWeaponComponent : public UActorComponent
Accessing Components in C++
In general, Actor components can be accessed by two Actor functions:
• Unfortunately, there’s no templated version of the function for getting
multiple components of a specific type.
• You should always check the return value for nullptr, in case the actor
doesn’t have the specified component.
template<class T> T* AActor::FindComponentByClass() const
TArray<UActorComponent*> AActor::GetComponentsByClass
(TSubclassOf<UActorComponent> ComponentClass) const;
Defensive Programming
• As always when writing code, you should be careful with null pointers
that can cause your game to crash when being dereferenced.
• Unreal Engine features a special function for this:
• IsValid will ensure that an object reference
 is not null
 is not pending kill (e.g. was destroyed)
 has not been garbage collected
• As UObject function, this is available almost everywhere in your code.
FORCEINLINE bool UObject::IsValid(const UObject *Test)
Spawning & Destroying Actors
• You can spawn new actors at runtime by calling one of various overloads
of the UWorld::SpawnActor function.
 Allows you to specify the type and transform of actor to spawn
 Allows you to specify additional spawn parameters, such as
o Owner of the new actor (for replication)
o Instigator of the new actor (for damage)
o How to handle spawn collisions (e.g. always spawn, adjust position, don’t
spawn)
• Access to the UWorld is provided by AActor::GetWorld() in turn.
• SpawnActor will return a nullptr if spawning fails, so you should always
check for its return value before proceeding.
• Actors can be destroyed again by calling AActor::Destroy()
UFUNCTION Specifiers
Specifier Description
BlueprintCallable Can be executed in a Blueprint graph.
BlueprintImplementableEvent Can be implemented in a Blueprint graph.
BlueprintNativeEvent Declares an additional function named the same as the
main function, but with _Implementation added to the
end, which is where code should be written. The auto-
generated code will call the "_Implementation" method if
no Blueprint override is found.
Just as classes and fields, functions can be annotated with UFUNCTION,
another Unreal Engine macro:
UFUNCTION Specifiers
Specifier Description
BlueprintPure Does not affect the owning object in any way and can be
executed in a Blueprint graph. Usually makes sense in
conjunction with C++ const.
Category Category of the function when displayed in Blueprint
editing tools.
Exec Can be executed from the in-game console.
Just as classes and fields, functions can be annotated with UFUNCTION,
another Unreal Engine macro:
UFUNCTION Specifiers
Specifier Description
Client Only executed on the client that owns the object on which the function is called. Declares an
additional function named the same as the main function, but with _Implementation
added to the end. The auto-generated code will call the _Implementation method when
necessary.
Server Only executed on the server. Declares an additional function (see Client). Requires
WithValidation.
WithValidation Declares an additional function named the same as the main function, but with _Validate
added to the end. This function takes the same parameters, and returns a bool to indicate
whether or not the call to the main function should proceed.
NetMulticast Executed both locally on the server, and replicated to all clients.
Just as classes and fields, functions can be annotated with UFUNCTION,
another Unreal Engine macro:
UFUNCTION Specifiers
Specifier Description
Reliable Replicated over the network, and is guaranteed to arrive regardless of
bandwidth or network errors.
Unreliable Replicated over the network, but can fail due to bandwidth limitations
or network errors.
Just as classes and fields, functions can be annotated with UFUNCTION,
another Unreal Engine macro:
Casting in Unreal
• In general, it’s recommended to cast Unreal references using the
templated Cast function.
 Makes use of Unreal reflections
 Simlar to dynamic_cast, returns a nullptr if the types don’t match
for (UActorComponent* ActorComponent : ActorComponents)
{
UPrimitiveComponent* PrimitiveComponent = Cast<UPrimitiveComponent>(ActorComponent);
if (PrimitiveComponent != nullptr)
{
// ...
}
}
Events
You can declare events to raise and listen to by declaring a delegate (function
signature) signature first, and the event itself afterwards:
(Note the commas between the parameter types and names.)
Then, the event can be raised by calling its Broadcast method.
DECLARE_DYNAMIC_MULTICAST_DELEGATE_ThreeParams
(FASCollisionDamageComponentDamageDealtSignature,
AActor*, Actor, float, Damage, AActor*, Target);
// ...
/** Event when the actor has dealt collision damage. */
UPROPERTY(BlueprintAssignable)
FASCollisionDamageComponentDamageDealtSignature OnDamageDealt;
// Notify listeners.
OnDamageDealt.Broadcast(GetOwner(), Damage, OtherActor);
Events
You can add event listeners by calling AddDynamic for an event
• The event handler function has to be a UFUNCTION
• Don’t do this in the constructor of a class – wait until BeginPlay instead
void UASCollisionDamageComponent::BeginPlay()
{
// ...
for (UActorComponent* ActorComponent : ActorComponents)
{
UPrimitiveComponent* PrimitiveComponent = Cast<UPrimitiveComponent>(ActorComponent);
PrimitiveComponent->OnComponentBeginOverlap.AddDynamic(this,
&UASCollisionDamageComponent::OnComponentBeginOverlap);
}
}
void UASCollisionDamageComponent::OnComponentBeginOverlap
(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent*
OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
UE_LOG(LogAS, Log, TEXT("Overlap!"));
}
Collision
• When a collision event occurs, both objects involved can be set to
affect or be affected by blocking, overlapping, or ignoring each other.
 Blocking occurs when both objects block each other.
o Blocking („hits“) can raise additional events by enabling „Simulation
Generates Hit Events“ for either actor
 Overlapping occurs if one actor is overlapping the other, and the
other is blocking the former.
o Overlapping will only raise events when enabling “Generate Overlap
Events” for both Actors for performance reasons
 All affected objects must have Collision Enabled for either of this to
happen
Collision
Collision
Collision & Hit Events
Overlap & Ignore
Overlap & Events
Handling Collisions in C++
• Collisions can be handled in C++ in various ways:
 By listening to UPrimitiveComponent events
o OnComponentHit
o OnComponentBeginOverlap
o OnComponentEndOverlap
 By listening to AActor events
o OnActorHit
o OnActorBeginOverlap
o OnActorEndOverlap
Handling Collisions in C++
• Collisions can be handled in C++ in various ways:
 By overriding AActor functions
o virtual void NotifyHit(class UPrimitiveComponent*
MyComp, AActor* Other, class UPrimitiveComponent*
OtherComp, bool bSelfMoved, FVector HitLocation,
FVector HitNormal, FVector NormalImpulse, const
FHitResult& Hit);
o virtual void NotifyActorBeginOverlap(AActor*
OtherActor);
o virtual void NotifyActorEndOverlap(AActor* OtherActor);
Projectiles
• As if Epic has been making shooters before, Unreal Engine features the
UProjectileMovementComponent for basic projectile movement
 Allows to specify initial speed or velocity, and maximum speed
 Can ignore gravity
 Can automatically rotate to „follow“ velocity
 Can follow targets („homing“)
 Can bounce
Taking Damage
• Actors provide a virtual function to allow gameplay code to handle damage as
desired:
• UDamageType is passed with FDamageEvent and allows you to define and handle
special types of damage, if necessary
• Instigator references to the player who was dealt damage, allowing for keeping
track of scores in match-based game modes
• Damage causer is the actual actor who dealt damage (e.g. projectile)
• Actors will notify interested listeners by raising AActor::OnTakeAnyDamage
• Damage can be negative
virtual float TakeDamage(float DamageAmount, struct FDamageEvent const&
DamageEvent, class AController* EventInstigator, AActor* DamageCauser);
Actor Lifespans
• AActor::InitialLifeSpan can be set (e.g. in editor or constructor)
to automatically destroy an Actor after a fixed timespan
• If you want to change the remaining lifespan of an Actor, use
AActor::SetLifeSpan instead.
 Passing 0.0f will prevent the actor from being destroyed
automatically.
Hint!
You can specify default values for UPROPERTY fields in the constructor of
a class.
Assignment #3 – Core Gameplay
1. Create a WeaponComponent for storing projectile references.
2. Create a HealthComponent for taking damage and destroying actors.
3. Bind input for firing projectiles.
4. Create a CollisionDamageComponent for dealing damage on overlap.
5. Create a Projectile blueprint, and add weapon and health to your
Character blueprint.
6. Store the kills each player achieved.
7. Bind input for respawning players
(APlayerController::ServerRestartPlayer).
8. Add a score limit to your game mode.
Bonus: Create a blueprint for health pickups.
References
• Epic Games. Properties. https://docs.unrealengine.com/en-
US/Programming/UnrealArchitecture/Reference/Properties/index.html, February
2020.
• Epic Games. Classes. https://docs.unrealengine.com/en-
US/Programming/UnrealArchitecture/Reference/Classes/index.html, February
2020.
• Epic Games. Functions. https://docs.unrealengine.com/en-
US/Programming/UnrealArchitecture/Reference/Functions/index.html, February
2020.
• Epic Games. Collision Overview. https://docs.unrealengine.com/en-
US/Engine/Physics/Collision/Overview/index.html, Feburary 2020.
• Epic Games. Dynamic Delegates. https://docs.unrealengine.com/en-
US/Programming/UnrealArchitecture/Delegates/Dynamic/index.html, February
2020.
See you next time!
https://www.slideshare.net/npruehs
https://github.com/npruehs/teaching-
unreal-engine/releases/tag/assignment03
npruehs@outlook.com
5 Minute Review Session
• When and why should you annotate a class field with UPROPERTY?
• How can you express class references in Unreal C++?
• How do you spawn and destroy actors?
• How can you listen to events in C++ in Unreal?
• Which collision types do exist in Unreal?
• How does the Unreal game framework support damage?

Mais conteúdo relacionado

Mais procurados

Optimizing unity games (Google IO 2014)
Optimizing unity games (Google IO 2014)Optimizing unity games (Google IO 2014)
Optimizing unity games (Google IO 2014)Alexander Dolbilov
 
Game Development with Unity
Game Development with UnityGame Development with Unity
Game Development with Unitydavidluzgouveia
 
Style & Design Principles 03 - Component-Based Entity Systems
Style & Design Principles 03 - Component-Based Entity SystemsStyle & Design Principles 03 - Component-Based Entity Systems
Style & Design Principles 03 - Component-Based Entity SystemsNick Pruehs
 
Intro to unreal with framework and vr
Intro to unreal with framework and vrIntro to unreal with framework and vr
Intro to unreal with framework and vrLuis Cataldi
 
Plug-ins & Third-Party SDKs in UE4
Plug-ins & Third-Party SDKs in UE4Plug-ins & Third-Party SDKs in UE4
Plug-ins & Third-Party SDKs in UE4Gerke Max Preussner
 
Render thead of hwui
Render thead of hwuiRender thead of hwui
Render thead of hwuiRouyun Pan
 
Game Development Step by Step
Game Development Step by StepGame Development Step by Step
Game Development Step by StepBayu Sembada
 
Forts and Fights Scaling Performance on Unreal Engine*
Forts and Fights Scaling Performance on Unreal Engine*Forts and Fights Scaling Performance on Unreal Engine*
Forts and Fights Scaling Performance on Unreal Engine*Intel® Software
 
Akka.NET 으로 만드는 온라인 게임 서버 (NDC2016)
Akka.NET 으로 만드는 온라인 게임 서버 (NDC2016)Akka.NET 으로 만드는 온라인 게임 서버 (NDC2016)
Akka.NET 으로 만드는 온라인 게임 서버 (NDC2016)Esun Kim
 
Game Programming 02 - Component-Based Entity Systems
Game Programming 02 - Component-Based Entity SystemsGame Programming 02 - Component-Based Entity Systems
Game Programming 02 - Component-Based Entity SystemsNick Pruehs
 
FMX 2017: Extending Unreal Engine 4 with Plug-ins (Master Class)
FMX 2017: Extending Unreal Engine 4 with Plug-ins (Master Class)FMX 2017: Extending Unreal Engine 4 with Plug-ins (Master Class)
FMX 2017: Extending Unreal Engine 4 with Plug-ins (Master Class)Gerke Max Preussner
 
Game Programming 07 - Procedural Content Generation
Game Programming 07 - Procedural Content GenerationGame Programming 07 - Procedural Content Generation
Game Programming 07 - Procedural Content GenerationNick Pruehs
 
Component-Based Entity Systems (Demo)
Component-Based Entity Systems (Demo)Component-Based Entity Systems (Demo)
Component-Based Entity Systems (Demo)Nick Pruehs
 
Game engines and Their Influence in Game Design
Game engines and Their Influence in Game DesignGame engines and Their Influence in Game Design
Game engines and Their Influence in Game DesignPrashant Warrier
 
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google MockICS
 
우리 프로젝트에 맞는 게임 엔진 - 테크니컬아트디렉터 김태근
우리 프로젝트에 맞는 게임 엔진 - 테크니컬아트디렉터 김태근우리 프로젝트에 맞는 게임 엔진 - 테크니컬아트디렉터 김태근
우리 프로젝트에 맞는 게임 엔진 - 테크니컬아트디렉터 김태근Visual Tech Dev
 
East Coast DevCon 2014: Concurrency & Parallelism in UE4 - Tips for programmi...
East Coast DevCon 2014: Concurrency & Parallelism in UE4 - Tips for programmi...East Coast DevCon 2014: Concurrency & Parallelism in UE4 - Tips for programmi...
East Coast DevCon 2014: Concurrency & Parallelism in UE4 - Tips for programmi...Gerke Max Preussner
 
Using Entity Command Buffers – Unite Copenhagen 2019
Using Entity Command Buffers – Unite Copenhagen 2019Using Entity Command Buffers – Unite Copenhagen 2019
Using Entity Command Buffers – Unite Copenhagen 2019Unity Technologies
 
Romero Blueprint Compendium
Romero Blueprint CompendiumRomero Blueprint Compendium
Romero Blueprint CompendiumUnreal Engine
 

Mais procurados (20)

Optimizing unity games (Google IO 2014)
Optimizing unity games (Google IO 2014)Optimizing unity games (Google IO 2014)
Optimizing unity games (Google IO 2014)
 
Game Development with Unity
Game Development with UnityGame Development with Unity
Game Development with Unity
 
Style & Design Principles 03 - Component-Based Entity Systems
Style & Design Principles 03 - Component-Based Entity SystemsStyle & Design Principles 03 - Component-Based Entity Systems
Style & Design Principles 03 - Component-Based Entity Systems
 
Intro to unreal with framework and vr
Intro to unreal with framework and vrIntro to unreal with framework and vr
Intro to unreal with framework and vr
 
Plug-ins & Third-Party SDKs in UE4
Plug-ins & Third-Party SDKs in UE4Plug-ins & Third-Party SDKs in UE4
Plug-ins & Third-Party SDKs in UE4
 
Render thead of hwui
Render thead of hwuiRender thead of hwui
Render thead of hwui
 
Game Development Step by Step
Game Development Step by StepGame Development Step by Step
Game Development Step by Step
 
OpenGL ES 3.1 Reference Card
OpenGL ES 3.1 Reference CardOpenGL ES 3.1 Reference Card
OpenGL ES 3.1 Reference Card
 
Forts and Fights Scaling Performance on Unreal Engine*
Forts and Fights Scaling Performance on Unreal Engine*Forts and Fights Scaling Performance on Unreal Engine*
Forts and Fights Scaling Performance on Unreal Engine*
 
Akka.NET 으로 만드는 온라인 게임 서버 (NDC2016)
Akka.NET 으로 만드는 온라인 게임 서버 (NDC2016)Akka.NET 으로 만드는 온라인 게임 서버 (NDC2016)
Akka.NET 으로 만드는 온라인 게임 서버 (NDC2016)
 
Game Programming 02 - Component-Based Entity Systems
Game Programming 02 - Component-Based Entity SystemsGame Programming 02 - Component-Based Entity Systems
Game Programming 02 - Component-Based Entity Systems
 
FMX 2017: Extending Unreal Engine 4 with Plug-ins (Master Class)
FMX 2017: Extending Unreal Engine 4 with Plug-ins (Master Class)FMX 2017: Extending Unreal Engine 4 with Plug-ins (Master Class)
FMX 2017: Extending Unreal Engine 4 with Plug-ins (Master Class)
 
Game Programming 07 - Procedural Content Generation
Game Programming 07 - Procedural Content GenerationGame Programming 07 - Procedural Content Generation
Game Programming 07 - Procedural Content Generation
 
Component-Based Entity Systems (Demo)
Component-Based Entity Systems (Demo)Component-Based Entity Systems (Demo)
Component-Based Entity Systems (Demo)
 
Game engines and Their Influence in Game Design
Game engines and Their Influence in Game DesignGame engines and Their Influence in Game Design
Game engines and Their Influence in Game Design
 
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
 
우리 프로젝트에 맞는 게임 엔진 - 테크니컬아트디렉터 김태근
우리 프로젝트에 맞는 게임 엔진 - 테크니컬아트디렉터 김태근우리 프로젝트에 맞는 게임 엔진 - 테크니컬아트디렉터 김태근
우리 프로젝트에 맞는 게임 엔진 - 테크니컬아트디렉터 김태근
 
East Coast DevCon 2014: Concurrency & Parallelism in UE4 - Tips for programmi...
East Coast DevCon 2014: Concurrency & Parallelism in UE4 - Tips for programmi...East Coast DevCon 2014: Concurrency & Parallelism in UE4 - Tips for programmi...
East Coast DevCon 2014: Concurrency & Parallelism in UE4 - Tips for programmi...
 
Using Entity Command Buffers – Unite Copenhagen 2019
Using Entity Command Buffers – Unite Copenhagen 2019Using Entity Command Buffers – Unite Copenhagen 2019
Using Entity Command Buffers – Unite Copenhagen 2019
 
Romero Blueprint Compendium
Romero Blueprint CompendiumRomero Blueprint Compendium
Romero Blueprint Compendium
 

Semelhante a Unreal Engine Basics 03 - Gameplay

Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptxRassjb
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java DevelopersYakov Fain
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And AnswerJagan Mohan Bishoyi
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answerlavparmar007
 
Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2ppd1961
 
Angular 16 – the rise of Signals
Angular 16 – the rise of SignalsAngular 16 – the rise of Signals
Angular 16 – the rise of SignalsCoding Academy
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programmingnirajmandaliya
 
Attributes & .NET components
Attributes & .NET componentsAttributes & .NET components
Attributes & .NET componentsBình Trọng Án
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMMario Fusco
 
Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)nirajmandaliya
 
C questions
C questionsC questions
C questionsparm112
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingVisual Engineering
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentJayaprakash R
 
object oriented programming language.pptx
object oriented programming language.pptxobject oriented programming language.pptx
object oriented programming language.pptxsyedabbas594247
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)rashmita_mishra
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2Leonid Maslov
 
Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_groupSkills Matter
 
Oop lect3.pptx
Oop lect3.pptxOop lect3.pptx
Oop lect3.pptxMrMudassir
 

Semelhante a Unreal Engine Basics 03 - Gameplay (20)

Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptx
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
 
Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2
 
Angular 16 – the rise of Signals
Angular 16 – the rise of SignalsAngular 16 – the rise of Signals
Angular 16 – the rise of Signals
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programming
 
Generic
GenericGeneric
Generic
 
Attributes & .NET components
Attributes & .NET componentsAttributes & .NET components
Attributes & .NET components
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
 
Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)
 
C questions
C questionsC questions
C questions
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App development
 
object oriented programming language.pptx
object oriented programming language.pptxobject oriented programming language.pptx
object oriented programming language.pptx
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
 
Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_group
 
Oop lect3.pptx
Oop lect3.pptxOop lect3.pptx
Oop lect3.pptx
 

Mais de Nick Pruehs

Unreal Engine Basics 06 - Animation, Audio, Visual Effects
Unreal Engine Basics 06 - Animation, Audio, Visual EffectsUnreal Engine Basics 06 - Animation, Audio, Visual Effects
Unreal Engine Basics 06 - Animation, Audio, Visual EffectsNick Pruehs
 
Game Programming - Cloud Development
Game Programming - Cloud DevelopmentGame Programming - Cloud Development
Game Programming - Cloud DevelopmentNick Pruehs
 
Game Programming - Git
Game Programming - GitGame Programming - Git
Game Programming - GitNick Pruehs
 
Eight Rules for Making Your First Great Game
Eight Rules for Making Your First Great GameEight Rules for Making Your First Great Game
Eight Rules for Making Your First Great GameNick Pruehs
 
Designing an actor model game architecture with Pony
Designing an actor model game architecture with PonyDesigning an actor model game architecture with Pony
Designing an actor model game architecture with PonyNick Pruehs
 
Game Programming 13 - Debugging & Performance Optimization
Game Programming 13 - Debugging & Performance OptimizationGame Programming 13 - Debugging & Performance Optimization
Game Programming 13 - Debugging & Performance OptimizationNick Pruehs
 
Scrum - but... Agile Game Development in Small Teams
Scrum - but... Agile Game Development in Small TeamsScrum - but... Agile Game Development in Small Teams
Scrum - but... Agile Game Development in Small TeamsNick Pruehs
 
What Would Blizzard Do
What Would Blizzard DoWhat Would Blizzard Do
What Would Blizzard DoNick Pruehs
 
School For Games 2015 - Unity Engine Basics
School For Games 2015 - Unity Engine BasicsSchool For Games 2015 - Unity Engine Basics
School For Games 2015 - Unity Engine BasicsNick Pruehs
 
Tool Development A - Git
Tool Development A - GitTool Development A - Git
Tool Development A - GitNick Pruehs
 
Game Programming 12 - Shaders
Game Programming 12 - ShadersGame Programming 12 - Shaders
Game Programming 12 - ShadersNick Pruehs
 
Game Programming 11 - Game Physics
Game Programming 11 - Game PhysicsGame Programming 11 - Game Physics
Game Programming 11 - Game PhysicsNick Pruehs
 
Game Programming 10 - Localization
Game Programming 10 - LocalizationGame Programming 10 - Localization
Game Programming 10 - LocalizationNick Pruehs
 
Game Programming 09 - AI
Game Programming 09 - AIGame Programming 09 - AI
Game Programming 09 - AINick Pruehs
 
Game Development Challenges
Game Development ChallengesGame Development Challenges
Game Development ChallengesNick Pruehs
 
Game Programming 08 - Tool Development
Game Programming 08 - Tool DevelopmentGame Programming 08 - Tool Development
Game Programming 08 - Tool DevelopmentNick Pruehs
 
Game Programming 06 - Automated Testing
Game Programming 06 - Automated TestingGame Programming 06 - Automated Testing
Game Programming 06 - Automated TestingNick Pruehs
 
Game Programming 05 - Development Tools
Game Programming 05 - Development ToolsGame Programming 05 - Development Tools
Game Programming 05 - Development ToolsNick Pruehs
 
Game Programming 04 - Style & Design Principles
Game Programming 04 - Style & Design PrinciplesGame Programming 04 - Style & Design Principles
Game Programming 04 - Style & Design PrinciplesNick Pruehs
 
Game Programming 03 - Git Flow
Game Programming 03 - Git FlowGame Programming 03 - Git Flow
Game Programming 03 - Git FlowNick Pruehs
 

Mais de Nick Pruehs (20)

Unreal Engine Basics 06 - Animation, Audio, Visual Effects
Unreal Engine Basics 06 - Animation, Audio, Visual EffectsUnreal Engine Basics 06 - Animation, Audio, Visual Effects
Unreal Engine Basics 06 - Animation, Audio, Visual Effects
 
Game Programming - Cloud Development
Game Programming - Cloud DevelopmentGame Programming - Cloud Development
Game Programming - Cloud Development
 
Game Programming - Git
Game Programming - GitGame Programming - Git
Game Programming - Git
 
Eight Rules for Making Your First Great Game
Eight Rules for Making Your First Great GameEight Rules for Making Your First Great Game
Eight Rules for Making Your First Great Game
 
Designing an actor model game architecture with Pony
Designing an actor model game architecture with PonyDesigning an actor model game architecture with Pony
Designing an actor model game architecture with Pony
 
Game Programming 13 - Debugging & Performance Optimization
Game Programming 13 - Debugging & Performance OptimizationGame Programming 13 - Debugging & Performance Optimization
Game Programming 13 - Debugging & Performance Optimization
 
Scrum - but... Agile Game Development in Small Teams
Scrum - but... Agile Game Development in Small TeamsScrum - but... Agile Game Development in Small Teams
Scrum - but... Agile Game Development in Small Teams
 
What Would Blizzard Do
What Would Blizzard DoWhat Would Blizzard Do
What Would Blizzard Do
 
School For Games 2015 - Unity Engine Basics
School For Games 2015 - Unity Engine BasicsSchool For Games 2015 - Unity Engine Basics
School For Games 2015 - Unity Engine Basics
 
Tool Development A - Git
Tool Development A - GitTool Development A - Git
Tool Development A - Git
 
Game Programming 12 - Shaders
Game Programming 12 - ShadersGame Programming 12 - Shaders
Game Programming 12 - Shaders
 
Game Programming 11 - Game Physics
Game Programming 11 - Game PhysicsGame Programming 11 - Game Physics
Game Programming 11 - Game Physics
 
Game Programming 10 - Localization
Game Programming 10 - LocalizationGame Programming 10 - Localization
Game Programming 10 - Localization
 
Game Programming 09 - AI
Game Programming 09 - AIGame Programming 09 - AI
Game Programming 09 - AI
 
Game Development Challenges
Game Development ChallengesGame Development Challenges
Game Development Challenges
 
Game Programming 08 - Tool Development
Game Programming 08 - Tool DevelopmentGame Programming 08 - Tool Development
Game Programming 08 - Tool Development
 
Game Programming 06 - Automated Testing
Game Programming 06 - Automated TestingGame Programming 06 - Automated Testing
Game Programming 06 - Automated Testing
 
Game Programming 05 - Development Tools
Game Programming 05 - Development ToolsGame Programming 05 - Development Tools
Game Programming 05 - Development Tools
 
Game Programming 04 - Style & Design Principles
Game Programming 04 - Style & Design PrinciplesGame Programming 04 - Style & Design Principles
Game Programming 04 - Style & Design Principles
 
Game Programming 03 - Git Flow
Game Programming 03 - Git FlowGame Programming 03 - Git Flow
Game Programming 03 - Git Flow
 

Último

How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 

Último (20)

How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 

Unreal Engine Basics 03 - Gameplay

  • 1. Unreal Engine Basics Chapter 3: Gameplay Nick Prühs
  • 2. Objectives • Learning how to expose class fields and functions to blueprints • Writing basic Unreal gameplay code, such as spawning actors, accessing components and listening for events • Getting familiar with gameplay concepts in the context of Unreal, such as damage and collision
  • 3. UPROPERTY • For the Unreal reflection system to be able to discover C++ fields, we need to annotate them with the UPROPERTY macro  This is required for the garbage collector to observe these properties. Forgetting to annotate a field of type UObject (or subtypes) can result in crashes when trying to access that field!  We can specify the behavior of the Unreal Editor with respect to these fields by adding additional specifiers as parameters to that macro. /** Class of the projectile to fire. */ UPROPERTY(EditDefaultsOnly) TSubclassOf<AActor> ProjectileClass;
  • 4. UPROPERTY – Accessibility Specifiers Specifier Description VisibleDefaultsOnly Only visible in property windows for archetypes, and cannot be edited. VisibleInstanceOnly Only visible in property windows for instances, not for archetypes, and cannot be edited. VisibleAnywhere Visible in all property windows, but cannot be edited. EditDefaultsOnly Can be edited by property windows, but only on archetypes. EditInstanceOnly Can be edited by property windows, but only on instances, not on archetypes. EditAnywhere Can be edited by property windows, on archetypes and instances.
  • 5. UPROPERTY – Accessibility & Other Specifiers Specifier Description BlueprintReadOnly Can be read by Blueprints, but not modified. BlueprintReadWrite Can be read or written from a Blueprint. Category Category of the property when displayed in Blueprint editing tools. Config Value can be saved to the .ini file associated with the class and will be loaded when created. Replicated Replicated over the network. ReplicatedUsing= FunctionName Replicated over the network, with a callback function which is executed when the property is updated. Must be a UFUNCTION (see later).
  • 6. Class References • Class references in Unreal are represented by pointers to UClass objects (similar to Type references in Java or C#) • To enforce compile-time type safety, you can use the template class TSubclassOf  The implementation of that template class will force you to include the header of the referenced type – a forward declaration won’t be enough and can lead to strange errors.  This will automatically cause Unreal Editor windows to filter dropdowns for selecting a class. /** Class of the projectile to fire. */ UPROPERTY(EditDefaultsOnly) TSubclassOf<AActor> ProjectileClass;
  • 7. UCLASS Specifiers Specifier Description Abstract Prevents the user from adding Actors of this class to Levels. Blueprintable Acceptable base class for creating Blueprints. NotBlueprintable Not an acceptable base class for creating Blueprints. (Default) BlueprintType Type that can be used for variables in Blueprints. Config Allowed to store data in a configuration file (.ini). Classes can be annotated with UCLASS, another Unreal Engine macro:
  • 8. UCLASS Specifiers Specifier Description BlueprintSpawnableCom ponent Component class can be spawned by a Blueprint. DisplayName Name of this node in a Blueprint. Another UCLASS specifier provides additional options: /** Adds a weapon to the actor, that fires projectiles. */ UCLASS(meta = (BlueprintSpawnableComponent)) class AWESOMESHOOTER_API UASWeaponComponent : public UActorComponent
  • 9. Accessing Components in C++ In general, Actor components can be accessed by two Actor functions: • Unfortunately, there’s no templated version of the function for getting multiple components of a specific type. • You should always check the return value for nullptr, in case the actor doesn’t have the specified component. template<class T> T* AActor::FindComponentByClass() const TArray<UActorComponent*> AActor::GetComponentsByClass (TSubclassOf<UActorComponent> ComponentClass) const;
  • 10. Defensive Programming • As always when writing code, you should be careful with null pointers that can cause your game to crash when being dereferenced. • Unreal Engine features a special function for this: • IsValid will ensure that an object reference  is not null  is not pending kill (e.g. was destroyed)  has not been garbage collected • As UObject function, this is available almost everywhere in your code. FORCEINLINE bool UObject::IsValid(const UObject *Test)
  • 11. Spawning & Destroying Actors • You can spawn new actors at runtime by calling one of various overloads of the UWorld::SpawnActor function.  Allows you to specify the type and transform of actor to spawn  Allows you to specify additional spawn parameters, such as o Owner of the new actor (for replication) o Instigator of the new actor (for damage) o How to handle spawn collisions (e.g. always spawn, adjust position, don’t spawn) • Access to the UWorld is provided by AActor::GetWorld() in turn. • SpawnActor will return a nullptr if spawning fails, so you should always check for its return value before proceeding. • Actors can be destroyed again by calling AActor::Destroy()
  • 12. UFUNCTION Specifiers Specifier Description BlueprintCallable Can be executed in a Blueprint graph. BlueprintImplementableEvent Can be implemented in a Blueprint graph. BlueprintNativeEvent Declares an additional function named the same as the main function, but with _Implementation added to the end, which is where code should be written. The auto- generated code will call the "_Implementation" method if no Blueprint override is found. Just as classes and fields, functions can be annotated with UFUNCTION, another Unreal Engine macro:
  • 13. UFUNCTION Specifiers Specifier Description BlueprintPure Does not affect the owning object in any way and can be executed in a Blueprint graph. Usually makes sense in conjunction with C++ const. Category Category of the function when displayed in Blueprint editing tools. Exec Can be executed from the in-game console. Just as classes and fields, functions can be annotated with UFUNCTION, another Unreal Engine macro:
  • 14. UFUNCTION Specifiers Specifier Description Client Only executed on the client that owns the object on which the function is called. Declares an additional function named the same as the main function, but with _Implementation added to the end. The auto-generated code will call the _Implementation method when necessary. Server Only executed on the server. Declares an additional function (see Client). Requires WithValidation. WithValidation Declares an additional function named the same as the main function, but with _Validate added to the end. This function takes the same parameters, and returns a bool to indicate whether or not the call to the main function should proceed. NetMulticast Executed both locally on the server, and replicated to all clients. Just as classes and fields, functions can be annotated with UFUNCTION, another Unreal Engine macro:
  • 15. UFUNCTION Specifiers Specifier Description Reliable Replicated over the network, and is guaranteed to arrive regardless of bandwidth or network errors. Unreliable Replicated over the network, but can fail due to bandwidth limitations or network errors. Just as classes and fields, functions can be annotated with UFUNCTION, another Unreal Engine macro:
  • 16. Casting in Unreal • In general, it’s recommended to cast Unreal references using the templated Cast function.  Makes use of Unreal reflections  Simlar to dynamic_cast, returns a nullptr if the types don’t match for (UActorComponent* ActorComponent : ActorComponents) { UPrimitiveComponent* PrimitiveComponent = Cast<UPrimitiveComponent>(ActorComponent); if (PrimitiveComponent != nullptr) { // ... } }
  • 17. Events You can declare events to raise and listen to by declaring a delegate (function signature) signature first, and the event itself afterwards: (Note the commas between the parameter types and names.) Then, the event can be raised by calling its Broadcast method. DECLARE_DYNAMIC_MULTICAST_DELEGATE_ThreeParams (FASCollisionDamageComponentDamageDealtSignature, AActor*, Actor, float, Damage, AActor*, Target); // ... /** Event when the actor has dealt collision damage. */ UPROPERTY(BlueprintAssignable) FASCollisionDamageComponentDamageDealtSignature OnDamageDealt; // Notify listeners. OnDamageDealt.Broadcast(GetOwner(), Damage, OtherActor);
  • 18. Events You can add event listeners by calling AddDynamic for an event • The event handler function has to be a UFUNCTION • Don’t do this in the constructor of a class – wait until BeginPlay instead void UASCollisionDamageComponent::BeginPlay() { // ... for (UActorComponent* ActorComponent : ActorComponents) { UPrimitiveComponent* PrimitiveComponent = Cast<UPrimitiveComponent>(ActorComponent); PrimitiveComponent->OnComponentBeginOverlap.AddDynamic(this, &UASCollisionDamageComponent::OnComponentBeginOverlap); } } void UASCollisionDamageComponent::OnComponentBeginOverlap (UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult) { UE_LOG(LogAS, Log, TEXT("Overlap!")); }
  • 19. Collision • When a collision event occurs, both objects involved can be set to affect or be affected by blocking, overlapping, or ignoring each other.  Blocking occurs when both objects block each other. o Blocking („hits“) can raise additional events by enabling „Simulation Generates Hit Events“ for either actor  Overlapping occurs if one actor is overlapping the other, and the other is blocking the former. o Overlapping will only raise events when enabling “Generate Overlap Events” for both Actors for performance reasons  All affected objects must have Collision Enabled for either of this to happen
  • 22. Collision & Hit Events
  • 25. Handling Collisions in C++ • Collisions can be handled in C++ in various ways:  By listening to UPrimitiveComponent events o OnComponentHit o OnComponentBeginOverlap o OnComponentEndOverlap  By listening to AActor events o OnActorHit o OnActorBeginOverlap o OnActorEndOverlap
  • 26. Handling Collisions in C++ • Collisions can be handled in C++ in various ways:  By overriding AActor functions o virtual void NotifyHit(class UPrimitiveComponent* MyComp, AActor* Other, class UPrimitiveComponent* OtherComp, bool bSelfMoved, FVector HitLocation, FVector HitNormal, FVector NormalImpulse, const FHitResult& Hit); o virtual void NotifyActorBeginOverlap(AActor* OtherActor); o virtual void NotifyActorEndOverlap(AActor* OtherActor);
  • 27. Projectiles • As if Epic has been making shooters before, Unreal Engine features the UProjectileMovementComponent for basic projectile movement  Allows to specify initial speed or velocity, and maximum speed  Can ignore gravity  Can automatically rotate to „follow“ velocity  Can follow targets („homing“)  Can bounce
  • 28. Taking Damage • Actors provide a virtual function to allow gameplay code to handle damage as desired: • UDamageType is passed with FDamageEvent and allows you to define and handle special types of damage, if necessary • Instigator references to the player who was dealt damage, allowing for keeping track of scores in match-based game modes • Damage causer is the actual actor who dealt damage (e.g. projectile) • Actors will notify interested listeners by raising AActor::OnTakeAnyDamage • Damage can be negative virtual float TakeDamage(float DamageAmount, struct FDamageEvent const& DamageEvent, class AController* EventInstigator, AActor* DamageCauser);
  • 29. Actor Lifespans • AActor::InitialLifeSpan can be set (e.g. in editor or constructor) to automatically destroy an Actor after a fixed timespan • If you want to change the remaining lifespan of an Actor, use AActor::SetLifeSpan instead.  Passing 0.0f will prevent the actor from being destroyed automatically.
  • 30. Hint! You can specify default values for UPROPERTY fields in the constructor of a class.
  • 31. Assignment #3 – Core Gameplay 1. Create a WeaponComponent for storing projectile references. 2. Create a HealthComponent for taking damage and destroying actors. 3. Bind input for firing projectiles. 4. Create a CollisionDamageComponent for dealing damage on overlap. 5. Create a Projectile blueprint, and add weapon and health to your Character blueprint. 6. Store the kills each player achieved. 7. Bind input for respawning players (APlayerController::ServerRestartPlayer). 8. Add a score limit to your game mode. Bonus: Create a blueprint for health pickups.
  • 32. References • Epic Games. Properties. https://docs.unrealengine.com/en- US/Programming/UnrealArchitecture/Reference/Properties/index.html, February 2020. • Epic Games. Classes. https://docs.unrealengine.com/en- US/Programming/UnrealArchitecture/Reference/Classes/index.html, February 2020. • Epic Games. Functions. https://docs.unrealengine.com/en- US/Programming/UnrealArchitecture/Reference/Functions/index.html, February 2020. • Epic Games. Collision Overview. https://docs.unrealengine.com/en- US/Engine/Physics/Collision/Overview/index.html, Feburary 2020. • Epic Games. Dynamic Delegates. https://docs.unrealengine.com/en- US/Programming/UnrealArchitecture/Delegates/Dynamic/index.html, February 2020.
  • 33. See you next time! https://www.slideshare.net/npruehs https://github.com/npruehs/teaching- unreal-engine/releases/tag/assignment03 npruehs@outlook.com
  • 34. 5 Minute Review Session • When and why should you annotate a class field with UPROPERTY? • How can you express class references in Unreal C++? • How do you spawn and destroy actors? • How can you listen to events in C++ in Unreal? • Which collision types do exist in Unreal? • How does the Unreal game framework support damage?