为pawn添加组件
2024年1月8日 2025年4月20日
pawn移动
之前的pawn移动, 其实是camera组件在移动
为pawn添加组件
GeometryPawn
-
静态网格体组件
static mesh
-
摄像机组件
camera
根组件的选择
之前绑定static mesh时, 将其设做根组件
现在有两种做法可供选择:
-
将scene组件作为根组件, 将static mesh和camera组件作为根组件附件
应用到scene组件的变换, 也会应用到static mesh和camera上 -
将static mesh作为根组件, 而camera作为static mesh附件, 此时, 移动static mesh, camera会一起移动. 反过来亦可
根组件和附件的选择, 会影响组件的最终变换矩阵, 其为根组件变换矩阵和附件变换矩阵的乘积
在头文件中添加前向声明
1class UCameraComponent; 2class UStaticMeshComponent;
在源文件中添加头文件
1#include "Components/StaticMeshComponent.h" 2#include "Camera/CameraComponent.h"
添加数据成员: 组件
protected
1UPROPERTY(VisibleAnywhere) 2UStaticMeshComponent *StaticMesh; 3 4UPROPERTY(VisibleAnywhere) 5UCameraComponent *Camera;
添加函数成员: 初始化组件
private
在构造函数中调用
初始化组件, 并挂在根组件下
1void AGeometryPawn::InitStaticMeshAndCameraComponent() 2{ 3 StaticMesh = CreateDefaultSubobject<UStaticMeshComponent>("StaticMeshComponent"); 4 Camera = CreateDefaultSubobject<UCameraComponent>("CameraComponent"); 5 6 StaticMesh->SetupAttachment(SceneComponent); 7 Camera->SetupAttachment(GetRootComponent()); 8}
实现虚函数: 了解切换pawn时函数的调用情况
调用时输出日志
用来了解切换pawn时, 对pawn对象的操作
使用pawn时, 调用PossessedBy
1void AGeometryPawn::PossessedBy(AController *NewController) { 2 Super::PossessedBy(NewController); 3 if (!NewController) return; 4 5 UE_LOG(LogGeometryPawn, Log, TEXT("%s possessed by %s"), *GetName(), *NewController->GetName()); 6}
切换pawn时, 调用UnPossessed
1void AGeometryPawn::UnPossessed() { 2 Super::UnPossessed(); 3 UE_LOG(LogGeometryPawn, Log, TEXT("%s is unpossessed"), *GetName()); 4}
创建并设置基于GeometryPawn的蓝图类
创建基于GeometryPawn的蓝图类
BP_GeometryPawn_Sphere
双击打开蓝图编辑器, 摄像机就是camera component的表示
为static mesh绑定模型sphere, 并应用材质
分离static mesh组件和camera组件
实际运行起来, 相当于第三视角, 可以看到static mesh的运动
可以为camera组件添加附件
按理说是无法看到添加的附件的
-
选中camera component
-
Add, 选择cube作为附件
-
可为cube应用材质