Multiplayer Shooter
December 22, 2022About 2 min
Multiplayer Shooter
https://www.udemy.com/course/unreal-engine-5-cpp-multiplayer-shooter
Peer-to-Peer, Client-Server
UE5 Uses an Authorirtative Client-Server Model
多人游戏连接
在打开场景的时候,可以设置当前场景是listen
状态,然后另一台电脑可以直接使用命令行Open Ip
进入,这有点东西。

同样可以使用代码加载关卡以及开启服务器:
UWorld* world = GetWorld();
if (world)
{
// /Game/ = Content floder
// ?listen, set the level is a listen server
world->ServerTravel("/Game/ThirdPerson/Maps/Lobby?listen");
}
加入服务器可以使用:
UGameplayStatics::OpenLevel(this, IPAddress);
或者使用:
APlayerController* playerController = GetGameInstance()->GetFirstLocalPlayerController();
if (playerController)
{
playerController->ClientTravel(IPAddress, ETravelType::TRAVEL_Absolute);
}
Online Subsystem

在Engine.ini
中设置使用哪个平台的服务器:

使用一下代码来获取网络系统:
IOnlineSubsystem* onlineSubsystem = IOnlineSubsystem::Get()
Session Interface
其中最主要的接口是Session,他的主要工作如下:

Session的生命周期以及对应的几个关键方法:

Online Subsystem Steam
https://docs.unrealengine.com/4.27/en-US/ProgrammingAndScripting/Online/Steam/
在插件中添加OnlineSubsystemSteam
插件,并且需要在.Build.cs
文件中的PublicDependencyModuleNames
添加:
"OnlineSubsystemSteam", "OnlineSubsystem"
Game Instance
- Spawned at game creation
- Not detroyed until the game is shut down
- Persists between levels
Game Instance Subsystem
- Created after the Game Instance is created
- Destroyed and garbage collected when the Game Instance is shut down
Game State

Travel in multiplayer

ENetRole
- ROLE_Authority :服务器
- ROLE_SimulatedProxy : 本地其他客户端
- ROLE_AutonomousProxy : 本地客户端
- ROLE_None
服务器上显示的角色类型如下图,其中最靠近屏幕的Pawn是本地控制角色:

客户端上显示的角色类型如下图,其中最靠近屏幕的Pawn是本地控制角色:

Replicated
UPROPERTY(Replicated)
复制变量,只能从服务器复制到客户端上。不能再客户端上修改了值,同步到其他客户端。
这个方法调用的地方:GetLifetimeReplicatedProps
:
UClass::ValidateRuntimeReplicationData()
UClass::SetUpRuntimeReplicationData()
UNetDriver::HandleNetDumpServerRPCCommand( const TCHAR* Cmd, FOutputDevice& Ar )