// Fill out your copyright notice in the Description page of Project Settings.#pragmaonce#include"CoreMinimal.h"#include"GameFramework/Actor.h"#include"MyActor.generated.h"UCLASS()classQUICKSTART_API AMyActor :public AActor
{GENERATED_BODY()public:UPROPERTY(VisibleAnywhere);
UStaticMeshComponent* VisualMesh;UPROPERTY(EditAnywhere, BlueprintReadWrite, Category ="Speed");float FloatSpeed =20.0f;UPROPERTY(EditAnywhere, BlueprintReadWrite, Category ="Speed");float RotationSpeed =20.0f;public:// Sets default values for this actor's propertiesAMyActor();protected:// Called when the game starts or when spawnedvirtualvoidBeginPlay() override;public:// Called every framevirtualvoidTick(float DeltaTime) override;};
cpp
// Fill out your copyright notice in the Description page of Project Settings.#include"MyActor.h"// Sets default valuesAMyActor::AMyActor(){// 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"));
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 spawnedvoidAMyActor::BeginPlay(){Super::BeginPlay();}// Called every framevoidAMyActor::Tick(float DeltaTime){Super::Tick(DeltaTime);//获取Actor当前位置及旋转
FVector NewLocation =GetActorLocation();
FRotator NewRotation =GetActorRotation();//获取自创建以来的游戏时间float RunningTime =GetGameTimeSinceCreation();//计算高度增量float DeltaHeight =(FMath::Sin(RunningTime + DeltaTime)-FMath::Sin(RunningTime));
NewLocation.Z += DeltaHeight * FloatSpeed;float DeltaRotation = DeltaTime * RotationSpeed;
NewRotation.Yaw += DeltaRotation;//将新的旋转Yaw以及高度设置给ActorSetActorLocationAndRotation(NewLocation, NewRotation);}