UE5 C++ 进阶学习 —— 02 - 小案例
配置 GameMode
声明构造函数。
// Fill out your copyright notice in the Description page of Project Settings.#pragma once#include "CoreMinimal.h"
#include "GameFramework/GameMode.h"
#include "FBGameMode.generated.h"/*** */
UCLASS()
class FLAPPYBIRD_API AFBGameMode : public AGameMode
{GENERATED_BODY()
public:// 声明构造函数AFBGameMode();
};
定义构造函数。
- 配置 GamePlay 框架的关键类(如 Default Pawn Class)。
- 注意:DefaultPawnClass 是 AGameMode 的成员变量(UClass* 类型),StaticClass() 是虚幻引擎为每个 UCLASS 生成的静态成员函数。返回该类的 UClass* 类型。
// Fill out your copyright notice in the Description page of Project Settings.#include "FlappyBird/Public/FBGameMode.h"#include "FlappyBird/Public/BirdPawn.h"AFBGameMode::AFBGameMode()
{DefaultPawnClass = ABirdPawn::StaticClass();
}
类型转换函数 Cast
// 格式:Cast<目标类型>(源指针)
目标类型* 结果指针 = Cast<目标类型>(源指针);- 如果转换成功(源指针指向的对象确实是目标类型或其派生类),返回有效的目标类型指针。
- 如果转换失败(类型不匹配),返回 nullptr。
获取玩家控制器
我们获取玩家控制器有两种方式。
在 APawn 类及其子类时:
- GetController() 是 APawn 类的成员函数,返回 AController* 类型(这个指针指向实际控制该 Pawn 的 Controller 对象)。如果该 APawn 是玩家控制的,那么指向 APlayerController(父类指针指向子类对象)。
// 获取玩家控制器
APlayerController* PC = Cast<APlayerController>(GetController());在其他类时:
- GetPlayerController() 是 UGameplayStatics 的静态成员函数。
- WordContextObject:通常为 this。
- PlayerIndex:玩家索引。
APlayerController* PC = UGameplayStatics::GetPlayerController(this, 0);注意:实际上就是蓝图中的 GetPlayerController。
