// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "CubeActor.generated.h"
UCLASS()
class STARTPROJECT_API ACubeActor : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
ACubeActor();
//使其在编辑器中可见
//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;
};
如果加上
UPROPERTY(VisibleAnywhere)
即在虚幻编辑器中可见
// Fill out your copyright notice in the Description page of Project Settings.
#include "CubeActor.h"
// Sets default values
ACubeActor::ACubeActor()
{
// 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引用填充新的静态网格组件,并将其附加到Actor上
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 ACubeActor::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
//每一帧运行一次
void ACubeActor::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
//获取位置
FVector NewLocation = GetActorLocation();
//获取角度
FRotator NewRotator = GetActorRotation();
//获取创建时间
float RunningTime = GetGameTimeSinceCreation();
//设置高度基准,sinx函数是周期函数。
float DeltaHeight = (FMath::Sin(RunningTime + DeltaTime) - FMath::Sin(RunningTime));
NewLocation.Z += DeltaHeight * 20.0f;
//设置位置
SetActorLocationAndRotation(NewLocation, NewRotator);
}
}
游戏运行:
UCLASS()可以使虚幻引擎识别类
GENERATED_BODY()加载前置条件
类初始化,构造函数ACubeActor::ACubeActor()运行,
调用父类BeginPlay()
调用Tick(float DeltaTime)