UE4cpp入门
p1
FloatingActor.h
#include "CoreMinimal.h"
此头文件包含UE4核心编程环境的普遍存在类型(包括FString / FName / TArray 等)
#include "GameFramework/Actor.h"
我们继承自Actor
#include "FloatingActor.generated.h"
这一行必须在最下面
p2
快速入门
FloatingActor.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "FloatingActor.generated.h"
UCLASS()
class UE4CPPSTART_API AFloatingActor : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
// 默认构造函数
AFloatingActor();
// 将变量公开到编辑器或蓝图
// VisibleAnywhere 修饰符设置该属性在任何地方都可见
UPROPERTY(VisibleAnywhere)
UStaticMeshComponent* VisualMesh;
// 添加变量进行控制
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "FloatingActor")
float FloatSpeed = 20.0f;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "FloatingActor")
float RotationSpeed = 20.0f;
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
// Fill out your copyright notice in the Description page of Project Settings.
#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;
// 创建一个指向该组件的指针
VisualMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));
// 把静态网格体组件附加到 RootComponent 上
VisualMesh->SetupAttachment(RootComponent);
/* 在编辑器中选择mash会更好
// 去资源文件夹下查找一个资源并加载
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 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 * FloatSpeed; //按FloatSpeed调整高度
float DeltaRotation = DeltaTime * RotationSpeed; //每秒旋转等于RotationSpeed的角度
NewRotation.Yaw += DeltaRotation;
SetActorLocationAndRotation(NewLocation, NewRotation);
}