UE5 C++ 笔记 GameplayAbilitySystem人物角色

摘要:该代码实现了一个支持Gameplay Ability System (GAS) 的Unreal Engine角色基类ANexusCharacterBase。它继承自ACharacter并实现了IAbilitySystemInterface接口,包含AbilitySystemComponent核心组件,设置默认角色移动参数(速度、跳跃等),并处理GAS在服务器端(PossessedBy)和客户端(OnRep_PlayerState)的初始化。角色配置了网络复制功能(ASCReplicationMode)

Nexus.Build.cs

cpp 复制代码
// Fill out your copyright notice in the Description page of Project Settings.

using UnrealBuildTool;

public class Nexus : ModuleRules
{
	public Nexus(ReadOnlyTargetRules Target) : base(Target)
	{
		PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
	
		PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore" });

		PrivateDependencyModuleNames.AddRange(new string[] { "GameplayAbilities","GameplayTasks","GameplayTags" });

		// Uncomment if you are using Slate UI
		// PrivateDependencyModuleNames.AddRange(new string[] { "Slate", "SlateCore" });
		
		// Uncomment if you are using online features
		// PrivateDependencyModuleNames.Add("OnlineSubsystem");

		// To include OnlineSubsystemSteam, add it to the plugins section in your uproject file with the Enabled attribute set to true
	}
}
cpp 复制代码
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once   // 防止头文件被重复包含(C++ 基础)

// ===== UE 核心最小依赖 =====
#include "CoreMinimal.h"

// ===== GAS(Gameplay Ability System)相关 =====
#include "AbilitySystemComponent.h"      // 能力系统组件(ASC)
#include "AbilitySystemInterface.h"      // GAS 接口,角色必须实现

// ===== 角色基类 =====
#include "GameFramework/Character.h"

// ===== UE 反射系统生成头文件 =====
#include "NexusCharacterBase.generated.h"

/**
 * ANexusCharacterBase
 * 
 * 这是一个支持 Gameplay Ability System(GAS)的角色基类
 * - 继承 ACharacter:拥有移动、跳跃、胶囊体、CharacterMovement
 * - 实现 IAbilitySystemInterface:让 GAS 能找到 AbilitySystemComponent
 */
UCLASS()
class NEXUS_API ANexusCharacterBase 
	: public ACharacter, public IAbilitySystemInterface
{
	GENERATED_BODY()

public:
	/** 构造函数
	 *  在 Actor 创建时调用
	 *  用于:创建组件、设置默认值
	 */
	ANexusCharacterBase();

	// ==================== GAS 核心组件 ====================

	/** Ability System Component(能力系统组件)
	 *  - GAS 的"核心大脑"
	 *  - 管理:技能(Ability)、属性(Attribute)、效果(Effect)
	 *  - VisibleAnywhere:蓝图中可见但不可编辑
	 *  - BlueprintReadOnly:蓝图可读取
	 */
	UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "AbilitySystem")
	class UAbilitySystemComponent* AbilitySystemComponent;

protected:
	/** GAS 的效果复制模式(多人网络相关)
	 *  Mixed:
	 *  - 自己:完整同步
	 *  - 其他人:最小必要同步
	 *  是官方和实际项目中最常用的模式
	 */
	UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "AbilitySystem")
	EGameplayEffectReplicationMode ASCReplicationMode 
		= EGameplayEffectReplicationMode::Mixed;

	// ==================== Actor 生命周期 ====================

	/** 游戏开始或角色生成完成时调用 */
	virtual void BeginPlay() override;

	/** 
	 *  当角色被 Controller(玩家或 AI)控制时调用
	 *  ⚠️ 只在服务器端调用
	 *  常用于:GAS 服务器初始化
	 */
	virtual void PossessedBy(AController* NewController) override;

	/**
	 *  PlayerState 同步到客户端后调用
	 *  ⚠️ 只在客户端调用
	 *  常用于:GAS 客户端初始化
	 */
	virtual void OnRep_PlayerState() override;

public:
	// ==================== 每帧与输入 ====================

	/** 每帧调用(Tick) */
	virtual void Tick(float DeltaTime) override;

	/** 绑定输入(键盘 / 手柄 / Enhanced Input) */
	virtual void SetupPlayerInputComponent(
		class UInputComponent* PlayerInputComponent) override;

	// ==================== GAS 接口实现 ====================

	/** 
	 * GAS 通过这个函数获取 AbilitySystemComponent
	 * 如果不实现这个函数,GAS 将无法正常工作
	 */
	virtual UAbilitySystemComponent* 
	GetAbilitySystemComponent() const override;
};
cpp 复制代码
// Fill out your copyright notice in the Description page of Project Settings.

#include "NexusCharacterBase.h"

// ===== 角色相关组件 =====
#include "Components/CapsuleComponent.h"              // 碰撞胶囊
#include "GameFramework/CharacterMovementComponent.h"// 角色移动组件

// ==================== 构造函数 ====================
ANexusCharacterBase::ANexusCharacterBase()
{
	// 允许 Tick(每帧调用 Tick 函数)
	// 如果不需要每帧逻辑,可以关闭以提高性能
	PrimaryActorTick.bCanEverTick = true;

	// ==================== 创建 GAS 组件 ====================

	// 创建 AbilitySystemComponent(ASC)
	// CreateDefaultSubobject 只能在构造函数中调用
	AbilitySystemComponent =
		CreateDefaultSubobject<UAbilitySystemComponent>(
			TEXT("AbilitySystemComponent"));

	// 启用网络复制(多人游戏必须)
	AbilitySystemComponent->SetIsReplicated(true);

	// 设置 GAS 的复制模式(Mixed / Full / Minimal)
	AbilitySystemComponent->SetReplicationMode(ASCReplicationMode);

	// ==================== 碰撞胶囊设置 ====================

	// 设置角色碰撞胶囊的尺寸
	// 半径:35,高度:90
	GetCapsuleComponent()->InitCapsuleSize(35.f, 90.0f);

	// ==================== 旋转控制 ====================

	// 不使用 Controller 的旋转来直接控制角色
	// 角色朝向由移动方向决定(更适合 ARPG / 动作游戏)
	bUseControllerRotationPitch = false;
	bUseControllerRotationYaw   = false;
	bUseControllerRotationRoll  = false;

	// ==================== 移动组件设置 ====================

	// 角色朝向移动方向
	GetCharacterMovement()->bOrientRotationToMovement = true;

	// 角色转向速度
	GetCharacterMovement()->RotationRate =
		FRotator(0.0f, 500.0f, 0.0f);

	// 跳跃力度
	GetCharacterMovement()->JumpZVelocity = 500.f;

	// 空中操控能力
	GetCharacterMovement()->AirControl = 0.35f;

	// 最大行走速度
	GetCharacterMovement()->MaxWalkSpeed = 500.f;

	// 手柄最小模拟行走速度
	GetCharacterMovement()->MinAnalogWalkSpeed = 20.0f;

	// 地面刹车减速度
	GetCharacterMovement()->BrakingDecelerationWalking = 2000.f;

	// 空中刹车减速度
	GetCharacterMovement()->BrakingDecelerationFalling = 1500.f;
}

// ==================== BeginPlay ====================
void ANexusCharacterBase::BeginPlay()
{
	// 调用父类 BeginPlay
	Super::BeginPlay();

	// 这里通常用于:
	// - 初始化属性
	// - 添加默认技能(服务器端)
}

// ==================== Tick ====================
void ANexusCharacterBase::Tick(float DeltaTime)
{
	// 调用父类 Tick
	Super::Tick(DeltaTime);

	// 每帧逻辑可以写在这里
}

// ==================== 输入绑定 ====================
void ANexusCharacterBase::SetupPlayerInputComponent(
	UInputComponent* PlayerInputComponent)
{
	// 调用父类输入绑定
	Super::SetupPlayerInputComponent(PlayerInputComponent);

	// 这里通常绑定:
	// - 移动
	// - 跳跃
	// - 技能输入(触发 Ability)
}

// ==================== 服务器端 GAS 初始化 ====================
void ANexusCharacterBase::PossessedBy(AController* NewController)
{
	// 调用父类逻辑
	Super::PossessedBy(NewController);

	// 服务器端初始化 GAS
	if (AbilitySystemComponent)
	{
		// 刷新 GAS 的 Actor 信息
		// 绑定 OwnerActor / AvatarActor
		AbilitySystemComponent->RefreshAbilityActorInfo();
	}
}

// ==================== 客户端 GAS 初始化 ====================
void ANexusCharacterBase::OnRep_PlayerState()
{
	// 调用父类逻辑
	Super::OnRep_PlayerState();

	// 客户端初始化 GAS
	if (AbilitySystemComponent)
	{
		// 初始化 Ability Actor 信息
		// 第一个 this:OwnerActor
		// 第二个 this:AvatarActor
		AbilitySystemComponent->InitAbilityActorInfo(this, this);
	}
}

// ==================== GAS 接口实现 ====================
UAbilitySystemComponent* 
ANexusCharacterBase::GetAbilitySystemComponent() const
{
	// 返回角色的 AbilitySystemComponent
	return AbilitySystemComponent;
}
相关推荐
wdfk_prog2 小时前
[Linux]学习笔记系列 -- [fs]fs_context
linux·笔记·学习
深蓝海拓2 小时前
PySide6从0开始学习的笔记(十六) 定时器QTimer
笔记·python·qt·学习·pyqt
ht巷子2 小时前
Qt:信号与槽
开发语言·c++·qt
千里马-horse2 小时前
Checker Tool
c++·node.js·napi
北辰水墨2 小时前
【算法篇】单调栈的学习
c++·笔记·学习·算法·单调栈
航Hang*2 小时前
第3章:复习篇——第3节:数据查询与统计
数据库·笔记·sql·mysql
惆怅客1232 小时前
在 vscode 中断点调试 ROS2 C++ 的办法
c++·vscode·调试·ros 2
么么...2 小时前
SQL 学习指南:从零开始掌握DQL结构化查询语言
数据库·经验分享·笔记·sql
眠りたいです2 小时前
Docker:镜像的运行实体-Docker Container
java·运维·c++·docker·容器·eureka