Character Movement-Related Mechanisms in Unreal Engine

Words: 1679

Introduction

This article is mainly used to organize the mechanisms related to movement in Unreal Engine.

The content may be excerpted from various articles, forums, documentation, etc., and is intended only as a record.

Basic Introduction

Movement is a very important and fairly complex module. UnrealEngine implements movement using the composition pattern; when describing the movement of an Actor, it means that an Actor with a movement component can move.

The base class for movement components is UMovementComponent, which provides basic movement functionality and has multiple subclasses with different functions. Some subclass movement components are dedicated to serving a special kind of Actor, such as ACharacter, which usually represents the player and whose corresponding movement component is UCharacterMovementComponent.

Although an Actor represents an entity in the World, it has no concept of position itself. An Actor’s position is given by its USceneComponents. Therefore, the essence of movement is that the Actor changes the position of a certain USceneComponent, usually the Actor’s RootComponent.

UMovementComponent has a property UpdatedComponent, which is used to set the USceneComponent modified by the movement component. A parameter bAutoRegisterUpdatedComponent is exposed to Blueprint; if set to true, then during component initialization it reads the Owner’s RootComponent and calls SetUpdatedComponent to set UpdatedComponent.

Movement Flow

Character movement under network replication needs to consider at least the following aspects:

  • No latency for player client operations
    • Movement input must be responded to directly and reported to the server
  • Position is authoritative on the server
    • Prevent cheating
  • Replicated movement should appear smooth
    • Position updates cannot be received every frame, so appropriate interpolation is required

Self Implementation

First, consider how one might implement it independently.

  • After receiving input locally, perform the movement locally first, and at the same time send the movement operation to the server
    • The information may include: current position, target position, etc.
  • After the server receives the movement operation, it executes the movement on the server and replicates the player’s displacement information to all clients
    • The information likewise includes: current position, target position, velocity, etc.
  • After other clients receive the movement information, they modify the character’s movement target and adjust the character’s position based on interpolation

Engine Implementation

The movement flow in Unreal Engine under network replication is similar to this, roughly as follows:

  • On each frame when TickComponent is executed, the acceleration and rotation change for the frame are calculated; afterward, for the locally controlled Character, ReplicateMoveToServer is called to replicate the movement to the server

  • ReplicateMoveToServer saves the movement to a list, then executes PerformMovement to pre-execute the movement operation locally.

  • Then it calls ServerMove to replicate the movement to the server, informing it of the movement parameters, the position the client itself moved to, and the timestamp

  • ServerMove is executed on the server; it compares the position declared by the client with the server’s position, and if the difference is too large, it calls ClientAdjustPosition to correct the position on the locally controlled client

  • If the client receives ClientAdjustPosition, it sets the client character’s position to the server’s position and marks bUpdatePosition as true, which will affect subsequent movement updates

  • When the client calls TickComponent again, if bUpdatePosition is present, it calls ClientUpdatePositionAfterServerUpdate to replay all movements that occurred after the movement adjustment on the server.

    The description of the movement replication flow can be found in the engine source file CharacterMovementComponent.h:

    Here’s how player movement prediction, replication and correction works in network games:

    Every tick, the TickComponent() function is called. It figures out the acceleration and rotation change for the frame, and then calls PerformMovement() (for locally controlled Characters), or ReplicateMoveToServer() (if it’s a network client).

    ReplicateMoveToServer() saves the move (in the PendingMove list), calls PerformMovement(), and then replicates the move to the server by calling the replicated function ServerMove() - passing the movement parameters, the client’s resultant position, and a timestamp.

    ServerMove() is executed on the server. It decodes the movement parameters and causes the appropriate movement to occur. It then looks at the resulting position and if enough time has passed since the last response, or the position error is significant enough, the server calls ClientAdjustPosition(), a replicated function.

    ClientAdjustPosition() is executed on the client. The client sets its position to the servers version of position, and sets the bUpdatePosition flag to true.

    When TickComponent() is called on the client again, if bUpdatePosition is true, the client will call ClientUpdatePosition() before calling PerformMovement(). ClientUpdatePosition() replays all the moves in the pending move list which occurred after the timestamp of the move the server was adjusting.

Player Input

Player input is also managed by a component, UInputComponent; typically, BindAxis can be called to register event responses.

Ultimately, this generally calls UPawnMovementComponent::AddInputVector to handle movement.

Locally Controlled Character Movement

In UE’s networking framework, characters are mainly divided into three types: ROLE_Authority, ROLE_AutonomousProxy, and ROLE_SimulatedProxy.

See also: Concepts related to network roles in Unreal Engine

On the client, the locally controlled character—that is, the Autonomous character—accepts control and then sends movement data to the server.

Each local movement generates an FSavedMove_Character, and a TArray<FSavedMovePtr> SavedMoves array is maintained, storing the movements the current player has already performed locally that have not yet been checked by the server.

If the server acknowledges some movements, those movements can be removed; if the check fails, exception handling can be performed based on them.

Protocol Choice

In UE, UDP is used as the transport protocol by default, which allows packets to be delivered as quickly as possible.

UDP does not guarantee delivery or ordering, but the application layer can avoid these problems where needed through design.

Server Replicates Movement to Clients

Basic Actor Replication Scheme

Actor itself supports movement replication. After the ReplicateMovement switch is enabled, when data such as the position and orientation of the Actor’s RootComponent changes, the data is replicated to simulated clients.

When a simulated client receives the replication, it simply sets its own position and orientation. Movement data replication has intervals, so this implementation causes the Actor to pop.

Character Movement Replication

To address the shortcomings of the basic Actor replication mode, CharacterMovementComponent specifically performs smoothing to make simulated character movement as smooth and natural as possible.

Character mainly has two components, Capsule and Mesh; Capsule is Chara

Key Concepts

UCharacterMovement

The character movement component is the most complex subclass and requires focused analysis.

  classDiagram
    class UCharacterMovementComponent {
        +IRVOAvoidanceInterface
        +INetworkPredictionInterface
    }
    UActorComponent <|-- UMovementComponent
    UMovementComponent <|-- UNavMovementComponent
    UNavMovementComponent <|-- UPawnMovementComponent
    UPawnMovementComponent <|-- UCharacterMovementComponent

FSavedMove_Character

Used to describe one movement of the player; it can be regarded as a snapshot of a single movement.

Its main properties are:

PropertyDescription
TimeStampThe time this movement occurred
DeltaTimeThe time used by this movement
CustomTimeDilationTime dilation coefficient, can be used for fast-forward and slow motion
StartPackedMovementModeMovementMode before the movement occurs
StartLocationPosition before the movement occurs
StartVelocityVelocity before the movement occurs
EndPackedMovementModeMovementMode after the movement occurs
SavedLocationPosition after the movement occurs
SavedVelocityVelocity after the movement occurs
AccelerationAcceleration used by the movement

In theory, as long as this data is available, the entire movement process can be reconstructed, and it can also be used for replay functionality.

ReplicateMoveToServer

First, it finds the earliest ImportantMove from SavedMoves (determined via IsImportantMove), that is, the most recently server-acknowledged Move with a significant difference.

After that, it creates and initializes an FSavedMove_Character. Then it executes PerformMovement, calculates the character’s post-operation properties, and sets the relevant information.

It then processes it according to whether it can be combined.

Delayed Move Sending

A Move may be delayed for a while and then sent to the server after being combined with a later Move. Therefore, before a newly created Move is sent to the server, it first checks whether it can be delayed.

First, it checks whether NetEnableMoveCombining is enabled; if not, it will not delay sending either.

It also checks whether the current Move can be delayed by checking whether the MovementMode before and after the Move has changed; if it has changed, the change also needs to be sent promptly. In other words, if this Move does not have a significant change, it can be delayed, and in theory the server’s calculation based on the previous information should produce the same result.

Then it calculates the currently expected movement update interval. Based on information such as current network speed and player count, it adjusts the baseline value ClientNetSendMoveDeltaTime to obtain the final interval. If the update interval has not yet been reached during Tick, it delays sending the Move and stores it in PendingMove for later processing.

CallServerMove

The function accepts two parameters: the newly created Move and the previously obtained ImportantMove (ImportantMove may be empty). It is not necessary to send the entire Move to the server; only key information such as position, rotation, and acceleration is needed, and this information is compressed.

Simply put, the compression process tries to sacrifice precision by merging some fields into a single data structure.

After that, it also calls ServerMoveOld to send some information from ImportantMove to the server, which can be simply understood as redundant insurance.

If PendingMove exists, it means there is an uncombined Move, and ServerMoveDual needs to be called to send two consecutive Moves at once. Otherwise, it means the send interval is relatively large, or PendingMove has already been combined, so ServerMode is called to send this Move.

ServerMoveOld

ServerMoveOld mainly serves as a redundant measure to prevent the server, when it newly receives movement data, from falling too far behind due to packet loss, causing the movement check to fail and thereby correcting the client’s position. ServerMoveOld allows the server to use the passed acceleration to roughly move quickly from the old position to the new position without validating the movement result.

TODO: How is security guaranteed?

TODO

  • Movement under physics simulation

  • How movement is sent via RPC

References

This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...