该文章为个人学习记录,意在巩固官网提供的学习内容(不喜勿喷!!!大佬有不对的地方欢迎指点),这里主要针对代码进行讨论,对底层及深入逻辑不做解析,新手友好!!!
原文链接:编程快速入门 | 虚幻引擎文档 (unrealengine.com)
↓ FloatingActor.h头文件
#pragma once
#include "CoreMinimal.h"//类似于C++里的ios、std包含一系列UE4引擎提供的常用类型,差不多可以理解为ue4底层逻辑经常用到的一些C++类型,UE4又重新拎出来做的一个集合!!!
#include "GameFramework/Actor.h"//UE4的框架类,后面的actor是根据你创建C++类时选择继承的父类对应的头文件
#include "FloatingActor.generated.h"//这个头文件加入了反射系统,在创建类时自动编译而成,在所有引用文件的最后(自行添加其他引用时,不能写在这个下面),有他可以使用ue4一系列宏。
UCLASS()//表示你创建的这个类可以被引擎识别,可以拥有ue4类的反射机制,括号里还可以填相关属性
class MYSTDPROJECT_API AFloatingActor : public AActor
{
GENERATED_BODY()//←这里都是ue4替你做的工作,可以简单理解为宏,ue4在原有的C++上进行了一系列魔改,这里不做深入探讨,建议拥抱度娘。
public://哪里都可以访问!!!
// Sets default values for this actor's properties
AFloatingActor();//默认构造函数
UPROPERTY(VisibleAnywhere)//VisibleAnywhere表示Detail面板可见
UStaticMeshComponent* VisualMesh;//声明一个静态网格组件
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="FloatingActor")//Editanywhere表示Detail面板可编辑,BlueprintReadWrite表示蓝图可读可写,Category类别分组
float FloatingSpeed = 0;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="FloatingActor")
float RotationSpeed = 0;
protected://类本身和子类可以访问
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
};
↓FloatingActor.cpp源文件
#include "FloatingActor.h"
// Sets default values
AFloatingActor::AFloatingActor()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;//表示此类为逐帧调用,false可以提高性能
VisualMesh= CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));//创建Component对象,要使用CreateDefaultSubobject模板函数"<创建的类型>(TEXT("组件名称"))"
VisualMesh->SetupAttachment(RootComponent);//绑定到rootcomponent根节点
static ConstructorHelpers::FObjectFinder<UStaticMesh> CubeVisualAsset(TEXT("/Game/StarterContent/Shapes/Shape_Cube.Shape_Cube"));//构建一个函数的静态助手,ConstructorHelpers可用于为资源或类寻找引用、以及创建并寻找组件
if (CubeVisualAsset.Succeeded())
{
VisualMesh->SetStaticMesh(CubeVisualAsset.Object);
VisualMesh->SetRelativeLocation(FVector(0.0f,0.0f,0.0f));
}
}
// Called when the game starts or when spawned
void AFloatingActor::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void AFloatingActor::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
FVector NewLocation=GetActorLocation();
FRotator NewRotation=GetActorRotation();
float RunningTime=GetGameTimeSinceCreation();
float DeltaHeight=(FMath::Sin(RunningTime+DeltaTime)-FMath::Sin(RunningTime));
NewLocation.Z+=DeltaHeight*FloatingSpeed;
float DeltaRotation=DeltaTime*RotationSpeed;
NewRotation.Yaw+=DeltaRotation;
SetActorLocationAndRotation(NewLocation,NewRotation);
}
ConstructorHelpers不明白看这里: