#defineFloatingActor.h// Fill out your copyright notice in the Description page of Project Settings.#pragmaonce#include"CoreMinimal.h"//一些核心的东西,比如一些数据类型#include"GameFramework/Actor.h"//Actor父类#include"FloatingActor.generated.h"//与ue4反射机制有关,必须放在所有头文件下方UCLASS()//可以理解为类的标识符,标识下面这是一个类//QUICKSTART_API 可以理解为一个命名空间,AFloatingActor才是类名,继承自AActorclassQUICKSTART_API AFloatingActor :public AActor
{GENERATED_BODY()//这个是宏,用来支持反射、序列化等C++本来没有的机制public:// Sets default values for this actor's properties//默认构造函数AFloatingActor();UPROPERTY(VisibleAnywhere)//将变量公开到编辑器或者蓝图,VisibleAnywhere修饰符设置该属性为任何地方都可见,是一个标识符//如果注释掉这句话,那么在编辑器中,就无法对这个变量的位置、缩放等进行设置
UStaticMeshComponent* VisualMesh;//静态网格体组件的指针,在此还未初始化protected:// Called when the game starts or when spawned//游戏一开始就调用的virtualvoidBeginPlay() override;public:// Called every frame//每帧调用virtualvoidTick(float DeltaTime) override;};
FloatingActor.cpp
#defineFloatingActor.cpp// Fill out your copyright notice in the Description page of Project Settings.#include"FloatingActor.h"// Sets default valuesAFloatingActor::AFloatingActor(){/*
构造函数,它在类首次创建时告诉该类如何初始化自身。
我们添加的代码将会在VisualMesh引用中填充新的StaticMeshComponent、 将它附加到Actor,
并将它设为 初学者内容包 资源中的立方体模型
*/// 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;//将Actor设置为逐帧调用Tick(),不需要则设为false
VisualMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));//创建一个静态网格体,并且赋值地址给指针
VisualMesh->SetupAttachment(RootComponent);//把静态网格体附加到根组件static ConstructorHelpers::FObjectFinder<UStaticMesh>CubeVisualAsset(TEXT("/Game/StarterContent/Shapes/Shape_Cube.Shape_Cube"));//查找一个资源的地址,并且创建一个变量存储//这部分如果注释了,不去查找资源,先创建好这么一个网格体,在编辑器中再赋予一个材质也是可以的if(CubeVisualAsset.Succeeded()){
VisualMesh->SetStaticMesh(CubeVisualAsset.Object);
VisualMesh->SetRelativeLocation(FVector(0.0f,0.0f,0.0f));}}// Called when the game starts or when spawnedvoidAFloatingActor::BeginPlay(){Super::BeginPlay();}// Called every framevoidAFloatingActor::Tick(float DeltaTime){/*
实时执行的代码。在此例中,它将使立方体在上下浮动的同时旋转。
*///调用父类方法Super::Tick(DeltaTime);//获取当前物体的位置
FVector NewLocation =GetActorLocation();//获取物体的旋转
FRotator NewRotation =GetActorRotation();//获取物体当前运行时间float RunningTime =GetGameTimeSinceCreation();//物体每帧高度,让物体的高度跟时间挂钩,就像sin函数图像那样,非常巧妙float DeltaHeight =(FMath::Sin(RunningTime + DeltaTime)-FMath::Sin(RunningTime));//把高度以20的系数进行缩放
NewLocation.Z += DeltaHeight *20.0f;//Scale our height by a factor of 20float DeltaRotation = DeltaTime *20.0f;//Rotate by 20 degrees per second
NewRotation.Yaw += DeltaRotation;//设置位置和旋转SetActorLocationAndRotation(NewLocation, NewRotation);}