UE学习C++(1)创建actor

创建新C++类

在 虚幻编辑器 中,点击 文件(File) 下拉菜单,然后选择 新建C++类...(New C++ Class...) 命令:

UE学习C++(1)创建actor_第1张图片

此时将显示 选择父类(Choose Parent Class) 菜单。可以选择要扩展的现有类,将其功能添加到自己的类。选择 Actor,因为其是可在场景中放置的最基本对象类型,然后点击 下一步(Next)

UE学习C++(1)创建actor_第2张图片

在 为新Actor命名(Name Your New Actor) 菜单中,将Actor命名为 FloatingActor,然后点击 创建类(Create Class)

UE学习C++(1)创建actor_第3张图片

编辑C++类

现在我们已创建C++类,将切换到Visual Studio并编辑代码。

在 Visual Studio 中,找到默认情况下显示在窗口左侧的 解决方案浏览器,然后用其找到 FloatingActor.h。在项目中,它将位于 Games> QuickStart > Source > QuickStart 下

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "create_actor.generated.h"

UCLASS()
class SPAWNDESTROY_API Acreate_actor : public AActor
{
	GENERATED_BODY()
	
public:	
	// Sets default values for this actor's properties
	Acreate_actor();

protected:
	// Called when the game starts or when spawned
	virtual void BeginPlay() override;

public:	
	// Called every frame
	virtual void Tick(float DeltaTime) override;
public:
	// 静态网格体成员
	UPROPERTY(VisibleAnywhere)
	UStaticMeshComponent* visualmesh;
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "FloatingActor")
	float FloatSpeed = 20.0f;

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "FloatingActor")
	float RotationSpeed = 20.0f;

};
#include "create_actor.h"

// Sets default values
Acreate_actor::Acreate_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;
	// UStaticMeshComponent 类型的默认子对象。这个组件将用于处理该 Actor 的静态网格模型。
	visualmesh = CreateDefaultSubobject(TEXT("Mesh"));
	// 将 visualmesh 组件附加到 Actor 的根组件(RootComponent)上,这意味着它将与该 Actor 一起移动、旋转或缩放。
	visualmesh->SetupAttachment(RootComponent);
	// FObjectFinder 类在游戏资源中查找一个名为 "Shape_Cube" 的静态网格模型资源(UStaticMesh)
	static ConstructorHelpers::FObjectFinder 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 Acreate_actor::BeginPlay()
{
	Super::BeginPlay();
	
}

// Called every frame
void Acreate_actor::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的角度
	
	SetActorLocationAndRotation(NewLocation, NewRotation);

}

你可能感兴趣的:(UE,java,开发语言)