1.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 QUICKSTART_API AFloatingActor : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
//默认构造函数
AFloatingActor();
//将变量公开到编辑器或蓝图
//VisibleAnywhere 修饰符设置该属性在任何地方都可见
UPROPERTY(VisibleAnywhere)
UStaticMeshComponent* VisualMesh;
protected:
// Called when the game starts or when spawned
//游戏一开始调用函数
virtual void BeginPlay() override;
public:
// Called every frame
//每帧调用
virtual void Tick(float DeltaTime) override;
};
2.FloatingActor.app
// Fill out your copyright notice in the Description page of Project Settings.
#include"QuickStart.h"
#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.
//将此Actor设为逐帧调用Tick(),如无需此功能,可关闭以提高性能
PrimaryActorTick.bCanEverTick = true;
//创建一个指向该组件的指针
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 spawned
void AFloatingActor::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void AFloatingActor::Tick(float DeltaTime)
{
//调用父类有参数的构造方法,也必须放在子类的构造方法(成员方法不可以)里面
//并且只能放在构造方法的首句,其中x,y,z是指的与父类此有参构造方法中参数数据类型相对应的子类的参数
Super::Tick(DeltaTime);
//获取物体当前位置
FVector NewLocation = GetActorLocation();
//获取物体当前的旋转
FRotator NewRotation = GetActorRotation();
//获取当前物体的运行时间
float RunningTime = GetGameTimeSinceCreation();
float DeltaHeight = (FMath::Sin(RunningTime + DeltaTime) - FMath::Sin(RunningTime));
//把高度以20的系数进行缩放
NewLocation.Z += DeltaHeight * 20.0f; //Scale our height by a factor of 20
float DeltaRotation = DeltaTime * 20.0f; //Rotate by 20 degrees per second
NewRotation.Yaw += DeltaRotation;
//设置位置和旋转
SetActorLocationAndRotation(NewLocation, NewRotation);
}
然后UE里点击编译,将正方体拖进去运行即可
最一开始出现问题后来上网查找发现自己app里没有加QuickStart的头文件 不清楚什么原因