Unreal Engine 4 learning general mobilization reading notes (2)
Referring to Unreal Engine 4 learning mobilization, the video operation has been completed step by step before, but the knowledge points have not been deeply understood and extracted. This chapter makes a more in-depth summary of the knowledge points for the previous operation.
This chapter is expanded by books rather than video chapters to have a more in-depth and comprehensive understanding of UE4, and expand the knowledge of reading the official website tutorial and API to explain.
Quick start
The quick start mainly introduces the UE4 blueprint and C + +, material, terrain, physics, lighting and AI. The content is relatively simple.
Download source code
-
Associated GitHub account: it needs to be on the personal account page https://www.unrealengine.com/dashboard/settings Fill in GitHub's user name
-
After receiving the email, confirm the invitation to join the Epic Game Github account
-
Official website githunb address: EpicGames/UnrealEngine: Unreal Engine source code (github.com)
-
UE4 Chinese Manual: Unreal Engine 4 documentation | Unreal Engine documentation (unrealengine.com)
Unity vs. UE4
-
UE4 audio only supports wav format
-
UE4 not only supports defining new objects by inheritance, but also supports defining components by C + + or blueprint
-
Write logic code in UE4
-
In the phantom, if you want to create an inherited class of UObject, it is initialized as follows:
UMyObject* NewObj = NewObject<UMyObject>();
-
The NewObject and SpawnActor functions can also work by giving a "template" object. The phantom engine creates a copy of the object instead of "creating a new object from zero". This copies all properties (property) and components of the object.
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); }
-
In phantom 4, we can use the constructor of the object to achieve the same effect.
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; } };
Note the use of CreateDefaultSubobject.
-
Type conversion
UPrimitiveComponent* Primitive = MyActor->GetComponentByClass(UPrimitiveComponent::StaticClass()); USphereComponent* SphereCollider = Cast<USphereComponent>(Primitive); if (SphereCollider != nullptr) { // ... }
Note the use of GetComponentByClass and Cast.
-
Destroy: myactor - > destroy();
-
Destroy GameObject / Actor (1 second delay): myactor - > setlifespan (1);
-
Disable GameObjects / Actors:
MyActor->SetActorHiddenInGame(true); // Disables collision components MyActor->SetActorEnableCollision(false); // Stops the Actor from ticking MyActor->SetActorTickEnabled(false);
-
Access GameObject / Actor through component: mycomponent - > getowner()
-
Access components through GameObject / Actor: umycomponent * mycomp = myactor - > findcomponentbyclass();
-
Find GameObjects / Actors:
// Find Actor by name (also works on UObjects) AActor* MyActor = FindObject<AActor>(nullptr, TEXT("MyNamedActor")); // Find Actors by type (needs a UWorld object) for (TActorIterator<AMyActor> It(GetWorld()); It; ++It) { AMyActor* MyActor = *It; // ... } // Find UObjects by type for (TObjectIterator<UMyObject> It; It; ++It) { UMyObject* MyObject = *It; // ... } // Find Actors by tag (also works on ActorComponents, use TObjectIterator instead) for (TActorIterator<AActor> It(GetWorld()); It; ++It) { AActor* Actor = *It; if (Actor->ActorHasTag(FName(TEXT("Mytag")))) { // ... } }
-
Tag GameObjects / Actors: MyActor.Tags.AddUnique(TEXT("MyTag");
-
Tag monobehaviors / actorcomponents: MyComponent.ComponentTags.AddUnique(TEXT("MyTag");
-
Compare the labels of GameObjects / Actors and monobehaviors / actorcomponents:
if (MyGameObject.CompareTag("MyTag")) { // ... } // Checks the tag on the GameObject it is attached to if (MyComponent.CompareTag("MyTag")) { // ... } // Checks if an Actor has this tag if (MyActor->ActorHasTag(FName(TEXT("MyTag")))) { // ... } // Checks if an ActorComponent has this tag if (MyComponent->ComponentHasTag(FName(TEXT("MyTag")))) { // ... }
-
Physics: rigid body vs. Primitive component: in illusion, any Primitive component (upprimitive component in C + +) can be a physical object. Some common Primitive components, such as ShapeComponent (capsule, sphere, box), StaticMeshComponent, and SkeletalMeshComponent.
-
Layer s vs channels: in Unity, they are called layers. Illusion is called Collision Channel
-
RayCast radiography vs RayTrace radiography
APawn* AMyPlayerController::FindPawnCameraIsLookingAt() { // You can use this to customize various properties about the trace FCollisionQueryParams Params; // Ignore the player's pawn Params.AddIgnoredActor(GetPawn()); // The hit result gets populated by the line trace FHitResult Hit; // Raycast out from the camera, only collide with pawns (they are on the ECC_Pawn collision channel) FVector Start = PlayerCameraManager->GetCameraLocation(); FVector End = Start + (PlayerCameraManager->GetCameraRotation().Vector() * 1000.0f); bool bHit = GetWorld()->LineTraceSingle(Hit, Start, End, ECC_Pawn, Params); if (bHit) { // Hit.Actor contains a weak pointer to the Actor that the trace hit return Cast<APawn>(Hit.Actor.Get()); } return nullptr; }
Pay attention to the use of linetracesinger
-
trigger
UCLASS()class AMyActor : public AActor{ GENERATED_BODY() // My trigger component UPROPERTY() UPrimitiveComponent* Trigger; AMyActor() { Trigger = CreateDefaultSubobject<USphereComponent>(TEXT("TriggerCollider")); // Both colliders need to have this set to true for events to fire Trigger.bGenerateOverlapEvents = true; // Set the collision mode for the collider // This mode will only enable the collider for raycasts, sweeps, and overlaps Trigger.SetCollisionEnabled(ECollisionEnabled::QueryOnly); } virtual void NotifyActorBeginOverlap(AActor* Other) override; virtual void NotifyActorEndOverlap(AActor* Other) override;};
Note the notifyactorbegionoverlap and NotifyActorEndOverlap virtual functions
-
Kinematic rigid bodies
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); }};
Note the use of SetPhysicsLinearVelocity
-
Input event
UCLASS()class AMyPlayerController : public APlayerController{ GENERATED_BODY() void SetupInputComponent() { Super::SetupInputComponent(); InputComponent->BindAction("Fire", IE_Pressed, this, &AMyPlayerController::HandleFireInputEvent); InputComponent->BindAxis("Horizontal", this, &AMyPlayerController::HandleHorizontalAxisInputEvent); InputComponent->BindAxis("Vertical", this, &AMyPlayerController::HandleVerticalAxisInputEvent); } void HandleFireInputEvent(); void HandleHorizontalAxisInputEvent(float Value); void HandleVerticalAxisInputEvent(float Value);};
Note the use of BindAction and BindAxis, and the callback function here starts with Handle
-
Unreal 4 does not handle exceptions. Instead, use the 'check()' function to trigger a serious assertion error. You can pass in an error message. If you just want to report an error but don't want to interrupt the whole program, you can use 'ensure()'. This logs an error message with the full call stack, but the program continues. If a debugger is currently attached, both functions will be tentative and enter the debugger.
-
Introductory case
-
Here we mainly introduce the basic composition and operation of UE4 editor, and build a simple scene by ourselves.
-
Using the material editor
- Download resources: https://docs.origin.unrealengine.com/latest/attachments/Engine/Content/QuickStart/1/2/QuickStartSampleAssets.zip , this resource cannot be downloaded in the browser, but only in Xunlei.
- Shading model - sub surface model: when light skips the surface, it can add color to the material to simulate the change of color. Demand: rock material under red light environment: the material shall reflect the influence of ambient light on the material.
-
Getting started with quick programming: here is a brief introduction to the use of AActor
-
Quick start to care: this chapter introduces the operation of using point light, spotlight and directional light
-
Terrain quick start
- Create a map: first create a normal material, using only basic colors and normal nodes. Use the terrain layer fusion node to fuse the map and normal information of the three layers.
- The terrain layer fusion node should not be an ordinary calculation node. The terrain file can find the information of the corresponding layer fusion node through the material information, and assign a value to it using the terrain layer fusion data file.
- Landscapelayercoords (terrain layer coordinates) should not be necessary. It should be used only when the UV of the material needs to be changed.
-
UMG quick start: the Demo uses widgets to display the blood volume of characters. It is worth noting that in this case, the method of binding the control UI to the attribute referenced by the sub object is used.
Create main menu
- Open levels in the menu: open level, remove from parent
- Execute game console command in the game: Execute Console Command r.setRes 1280x720 (jump screen size)
- Set Input Mode Game Only
- Pause the game
- Set Game Pause pauses the game itself
- Show Mouse Cursor
- Set Input Mode UI Only receives input events
-
Introduction to behavior tree
- Aicontroller: execute the behavior tree and update the blackboard value
- Behavior tree: defines how AI behaves
- Blackboard: data reference of AI behavior tree, equivalent to structure
- Behavior tree composition node: the decision mode node of the behavior tree, which is divided into selector, sequence and simple parallel (service can be used instead)
- Selector: for example, there are three solutions for a task. The selector is equivalent to the scheme list. The scheme in the selector has priority. AI will try to execute from the first scheme. As long as one is successful, execution will end.
- Sequence: for example, the execution of a task is completed after three steps a, B and C. the tasks in the execution sequence have sequence, and AI will execute in sequence. As long as one fails, the execution fails and terminates.
- Simple parallel: it has a main character and a background branch. When the main task is executed, the background branch will be executed at the same time until the background branch ends. For example, when the enemy finds the player, he moves to the player and starts shooting. When the player cannot be found, the shooting will stop.
- Navigation mesh boundary volume: defines the volume of the AI's moving range
- AI perception component: by defining AI auditory configuration and visual configuration, AI will execute the On Target Perception Updated callback function when it finds players.
- Task: the action executed by AI. You can customize the task. The built-in common tasks include: Rotate to face, Move To, Wait
- Service: it is equivalent to a task. It is attached to the composite node and executed with the composite node first. It is mainly used to update the data of the blackboard. Using the service, all tasks in all non leaf nodes can be hidden.
- Decorator: the decorator can decide which branch to enter according to the decision conditions. When the conditions defined by the decorator are executed, it can decide whether to terminate the low priority task and execute the branch.
-
Common decorators
- Custom decorator
- Blackboard decorator
- Timelimit decorator (limit the execution time of the execution node)
- IsAtLocation decorator (judge whether the AIActor is within the specified position range)
Blueprint application
Blueprints play an important role in UE4. Compared with C + + programming, blueprints have the following advantages:
- Easy to learn.
- Many functions of the blueprint are simplified and easy to remember and query.
- Fast compilation with fewer errors.
However, it should also be recognized that the blueprint is only the built-in script language of UE4, not a technology, and can not directly solve specific problems. Therefore, we should not study the blueprint too much, as long as we can master the common operations.
First familiarize yourself with the important shortcut keys: Alt + Shift + O: locate files. This will help a lot when there are too many project files. Of course, it's best to have a good specification for your file name.
General script
- event
- EventLevelReset: executed when the level is restarted, only on the server. For example, it is useful when the player dies and the level does not need to be reloaded.
- Event Actor Begin Overlap: when two actors overlap. Generate Overlap Event is required to be True.
- Event Actor End Overlap: two actors stop overlapping.
- Event Hit: when the Actor collides. Generate Hit Events is required to be True
- Event Any Damage: triggered only when the server is injured.
- Event Point Damage: point damage, such as melee weapons
- Event radioactive damage
- Event Actor Begin Cursor Over: when the mouse cursor hovers
- Event Actor End Cursor Over: when the mouse cursor leaves the Actor
- Event Begin Play: start the game
- Event End Play
- Event Destroyed
- Event Tick
- Event Receive Draw HUD: only used for Blueprints inherited from HUD, used to draw HUD
- Custome Event...
- structural morphology
- Split & combine structure pins
- Split structure: break
- Component structure: make
- set members in struct
Construction blueprint
- Macros and functions
- Macros are the same as merge nodes, but macros can be reused, and macros can have multiple output execution pins.
- Delay can be used only for merging nodes and macros, but not for functions.
- Functions can define local variables, while macros cannot define local variables.
- The function uses value transfer for variable types by default, or can be set to reference transfer; Macros can only be passed by reference.
- Blueprint debugging
- Breakpoint with F9
- You can open the debug window to view all the values being watch ed
- Blueprint direct communication
- Obtain the reference of the opposite blueprint by direct or variable assignment.
- Directly call the other blueprint function.
- Event allocator
- The event distributor can define parameters and implement dependency inversion.
- Blueprint interface
- The blueprint interface enforces what functions the blueprint can achieve.
- The blueprint interface can also separate the sending and receiving of blueprints, but the sender must have a reference to the object to be sent.
- The blueprint caller does not need to know whether it can be correctly converted to the corresponding blueprint interface. If it cannot be converted, the function will not be called.
- Blueprint interfaces can only be added to actor s, and event distributors can be added to game frameworks, UMG, etc.
Blueprint technical guide
-
Expose game elements to blueprint
UPROPERTY
- BlueprintReadOnly
- BlueprintReadWrite
- BlueprintAssignable: multicast delegate assignable
- BlueprintCallable: multicast delegate callable
//1. Declare multicast delegation_ DYNAMIC_ MULTICAST_ DELEGATE_ OneParam(FOnKingDeathSignature, AKing*, DeadKing);// 2. Define the multicast delegation variable upper property (blueprintassignable) / / the blueprint can dynamically assign the event FOnKingDeathSignature OnKingDeath to the delegation// The multicast delegate instance invokes the method //3. on the delegate after Broadcast to call the multicast delegate OnKingDeath.Broadcast(this);//4. Bind the multicast delegate Bind Event to OnKingDeath in the blueprint
UFUNCTION
- BlueprintCallable
- BlueprintPure
- Blueprintimplementationableevent: a function can be declared in C + + (it cannot be defined, but the blueprint is rewritten). The function is called in C + +, and the blueprint rewritten implements the function
- BlueprintNativeEvent: a function can be declared and defined in C + + (defined by xxx_implementation), called in C + +, and implemented by blueprint rewriting (blueprint can rewrite or not rewrite C + + parent functions)
When blueprintimplementationableevent or BlueprintNativeEvent has no return value, it is used as an event in the blueprint. When there is a return value, it is used as a function.
-
some suggestions
-
ExpandEnumAsExecs: multi pin functions can be implemented.
UENUM(BlueprintType)enum class BranchOutput : uint8{ Branch0, Branch1, Branch2,};UFUNCTION(BlueprintCallable, Category = "methods", Meta = (ExpandEnumAsExecs = "Branches")) void FunExpandEnumAsExecs(int32 Input, BranchOutput& Branches); void AMyActor::FunExpandEnumAsExecs(int32 Input, BranchOutput& Branches){ if (Input == 0) { Branches = BranchOutput::Branch0; } else if(Input == 1) { Branches = BranchOutput::Branch1; } else { Branches = BranchOutput::Branch2; }}
-
Fleetactioninfo can implement some operations that need to wait: the underlying principle is to query the status every frame, and then perform further operations when subsequent operations can be performed.
/** * Perform a latent action with a delay (specified in seconds). Calling again while it is counting down will be ignored. * * @param WorldContext World context. * @param Duration length of delay (in seconds). * @param LatentInfo The latent action. */ UFUNCTION(BlueprintCallable, Category="Utilities|FlowControl", meta=(Latent, WorldContext="WorldContextObject", LatentInfo="LatentInfo", Duration="0.2", Keywords="sleep")) static void Delay(UObject* WorldContextObject, float Duration, struct FLatentActionInfo LatentInfo );void UKismetSystemLibrary::Delay(UObject* WorldContextObject, float Duration, FLatentActionInfo LatentInfo ){ if (UWorld* World = GEngine->GetWorldFromContextObject(WorldContextObject, EGetWorldErrorMode::LogAndReturnNull)) { FLatentActionManager& LatentActionManager = World->GetLatentActionManager(); if (LatentActionManager.FindExistingAction<FDelayAction>(LatentInfo.CallbackTarget, LatentInfo.UUID) == NULL) { LatentActionManager.AddNewAction(LatentInfo.CallbackTarget, LatentInfo.UUID, new FDelayAction(Duration, LatentInfo)); } }}// FDelayAction// A simple delay action; counts down and triggers it's output link when the time remaining falls to zeroclass FDelayAction : public FPendingLatentAction{public: float TimeRemaining; FName ExecutionFunction; int32 OutputLink; FWeakObjectPtr CallbackTarget; FDelayAction(float Duration, const FLatentActionInfo& LatentInfo) : TimeRemaining(Duration) , ExecutionFunction(LatentInfo.ExecutionFunction) , OutputLink(LatentInfo.Linkage) , CallbackTarget(LatentInfo.CallbackTarget) { } virtual void UpdateOperation(FLatentResponse& Response) override { TimeRemaining -= Response.ElapsedTime(); Response.FinishAndTriggerIf(TimeRemaining <= 0.0f, ExecutionFunction, OutputLink, CallbackTarget); } #if WITH_EDITOR // Returns a human readable description of the latent operation's current state virtual FString GetDescription() const override { static const FNumberFormattingOptions DelayTimeFormatOptions = FNumberFormattingOptions() .SetMinimumFractionalDigits(3) .SetMaximumFractionalDigits(3); return FText::Format(NSLOCTEXT("DelayAction", "DelayActionTimeFmt", "Delay ({0} seconds left)"), FText::AsNumber(TimeRemaining, &DelayTimeFormatOptions)).ToString(); }#endif};
-
If possible, try to put functions in a shared library: inherit from UBluepintFunctionLibrary
-
Marking the function const can also make the blueprint node without pins.
-
-
The new version supports the original blueprint to reduce the call of blueprint virtual machine.
Online Session node Session
- Create Session: Create Session
- Find Session: Find Session
- Join Session: Join Session
- Destroy Session: Destroy Session
- Network error: Event Network Error
- Other errors: Event Travel Error
Bitmask blueprint variable
- When Bitmask mask is enabled for both enumeration type and integer type, integer type can be specified to the enumeration type.
- You can use OR, AND, XOR, NOT operations.
Blueprint application practice
- Random flow and random flow function
- Random stream is a pseudo-random number. Using the same seed will produce the same random value when calling the same function.
- Timeline
- Timeline can be used, but values, vectors, events (discrete, get a pulse signal at a specific time), colors
Animation design
Animation is very important in the game, but some animation in UE4 lacks some key points. At present, we only know some common animation technologies. Later, when actual research is needed, further study will be carried out.
First, explain some operations and meanings in the following course videos
-
Edit animation layer: indicates that you can modify the bones in the animation frame as you think.
-
Curve driven Animation: you can select some of the animation frames to form a gap animation.
-
Use sub animation example: Currently, the new version cannot create sub animation blueprint, so no research is needed
-
Create dynamic animation: use Anim Dynamics node to realize the physical vibration of some bones.
-
Create mixed space Animation: it is often used to create the transition of character actions in 3D, such as the process from walking to running
-
Create layered Animation: it is used in some gun battle or battle type games. Layered blend per bone is used. Starting from the set bone, including its sub bones, the animation of "Blend Pose 0" is used to replace the animation of "Base Pose". Because the default bone arrangement of UE4 is relatively special, this method can be used to simply realize that the bone on the spine is controlled by another posture, so as to realize the animation of ordinary gun battle.
-
Create a cut-off Animation: often used in the beginning, end, or some narrative segments of the game
Specific items commonly used in the project include:
- Bone slot: right click on the bone panel, add a slot, and then you can bind the model to the slot with attachactorcomponent.
- Animation controller: you can play different animations according to attribute control.
- Blend space: you can get excessive animation in two animations according to one parameter.
- Animated Montage:
- It can be used to break the animation: PlayAnimMontage plays the montage and inserts the animation montage clip between the state machine and the output to break the previous animation output.
- Add events: such as playing sound, particle effects or custom events at a frame to notify the animation blueprint
- Layered Animation: mainly used in shooting games.
- Cut scene animation: it is used in narrative clips and can be played directly after making resources. It is unclear whether the objects in the scene can be adjusted in time in the cut scene animation.