C++ 在 Unreal 中为游戏增加实时音视频互动的教程详解

2020-05-29 11:02:26于丽

创建 VideoCallPlayerController 创建 EnterChannelWidget C++ Class 创建 VideoViewWidget C++ Class 创建 VideoCallViewWidget C++ Class 创建 VideoCallWidget C++ Class 创建 BP_EnterChannelWidget blueprint asset 创建 BP_VideoViewWidget Asset 创建 BP_VideoCallViewWidget Asset 创建 BP_VideoCallWidget Asset 创建 BP_VideoCallPlayerController blueprint asset 创建 BP_AgoraVideoCallGameModeBase Asset 修改 Game Mode

创建 VideoCallPlayerController

为了能够将我们的Widget Blueprints添加到Viewport中,我们创建我们的自定义播放器控制器类。

在 "内容浏览器 "中,按 "Add New "按钮,选择 "新建C++类"。在 "添加C++类 "窗口中,勾选 "显示所有类 "按钮,并输入PlayerController。按 "下一步 "按钮,给类命名为 VideoCallPlayerController。按Create Class按钮。

//VideoCallPlayerController.h
#include "CoreMinimal.h"
#include "GameFramework/PlayerController.h"
#include "VideoCallPlayerController.generated.h"
UCLASS()
class AGORAVIDEOCALL_API AVideoCallPlayerController : public APlayerController
{
 GENERATED_BODY()
public:
};

这个类是 BP_VideoCallPlayerController 的 Blueprint Asset 的基类,我们将在最后创建。

增加需要的 Include

在 VideoCallPlayerController.h 文件的头部包括了所需的头文件。

//VideoCallPlayerController.h
#include "CoreMinimal.h"
#include "GameFramework/PlayerController.h"
#include "Templates/UniquePtr.h"
#include "VideoCall.h"
#include "VideoCallPlayerController.generated.h"
//VideoCallPlayerController.cpp
#include "Blueprint/UserWidget.h"
#include "EnterChannelWidget.h"
#include "VideoCallWidget.h"

类声明

为下一个类添加转发声明:

//VideoCallPlayerController.h
class UEnterChannelWidget;
class UVideoCallWidget;

稍后我们将跟进其中的两个创建,即 UEnterChannelWidget 和 UVideoCallWidget。

添加成员变量

现在,在编辑器中添加成员引用到 UMG Asset 中。

//VideoCallPlayerController.h
...
UCLASS()
class AGORAVIDEOCALL_API AVideoCallPlayerController : public APlayerController
{
 GENERATED_BODY()
public:
 UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Widgets")
 TSubclassOf<class UUserWidget> wEnterChannelWidget;
 UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Widgets")
 TSubclassOf<class UUserWidget> wVideoCallWidget;
 ...
};

变量来保持创建后的小部件,以及一个指向VideoCall的指针。

//VideoCallPlayerController.h
...
UCLASS()
class AGORAVIDEOCALL_API AVideoCallPlayerController : public APlayerController
{
 GENERATED_BODY()
public:
 ...
 UEnterChannelWidget* EnterChannelWidget = nullptr;
 UVideoCallWidget* VideoCallWidget = nullptr;
 TUniquePtr<VideoCall> VideoCallPtr;
 ...
};