<L2>c++实现物体旋转漂浮和打印字符串到屏幕

441 阅读2分钟

c++实现物体旋转漂浮(类似可拾取的物品效果)

1.创建c++类 Floating Actor

生成 Floating Actor.h 和Floating Actor.cpp 文件

2.Floating Actor.h

可以将它视作C++类的目录之类的东西。 要开始编译任何新功能,必须首先声明在此文件中使用的所有新 变量函数

AFloatingActor() 的声明下面添加下列代码:

	UPROPERTY(VisibleAnywhere) //使用了UPROPERTY宏命令,使他在虚幻编辑器中可见
	UStaticMeshComponent* VisualMesh;//声明了一个静态网格组件

	//产生在编辑器中可见的字段
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "FloatingActor")
	float FloatSpeed = 20.0f;

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

UPROPERTY关键词,用于指定属性与引擎和编辑器诸多方面的相处方式。

如:

  • 参数作用
    EditAnywhere说明此属性可通过属性窗口在原型和实例上进行编辑。
    VisibleAnywhere说明此属性在所有属性窗口中可见,但无法被编辑。
    BlueprintReadWrite可从蓝图读取或写入此属性。

3.Floating Actor.cpp

AFloatingActor::AFloatingActor() 中添加代码:

// 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"));
	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));
	}
	
}

其中寻找资产的路径 可以直接将虚幻编辑器的模型拖过来直接生成路径。

AFloatingActor::Tick(float DeltaTime) 中添加代码

// Called every frame
void AFloatingActor::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

	//新建一个向量  并存储了actor的当前位置
	FVector NewLocation = GetActorLocation();  
	//新建了一个向量 并存储了actor的当前旋转
	FRotator NewRotation = GetActorRotation(); 
	//自创建此 Actor 以来的秒数(以游戏时间计),相对于以秒为单位的获取游戏时间。
	float RunningTime = GetGameTimeSinceCreation(); 
	//FMath::Sin 计算标量值的正弦   这里用正弦是为了将数值限定在 [-1,1]之间 
	float DeltaHeight = (FMath::Sin(RunningTime + DeltaTime) - FMath::Sin(RunningTime));
	//将DeltaHeight打印到屏幕 通过打印发现 这个值更加小
	UKismetSystemLibrary::PrintString(this, UKismetStringLibrary::Conv_FloatToString(DeltaHeight));
	NewLocation.Z += DeltaHeight * FloatSpeed;          //按FloatSpeed调整高度
	float DeltaRotation = DeltaTime * RotationSpeed;    //每秒旋转等于RotationSpeed的角度

	NewRotation.Yaw += DeltaRotation;
	//设置actor的旋转和位置
	SetActorLocationAndRotation(NewLocation, NewRotation);
}

其中使用UKismetSystemLibrary::PrintString需要添加

#include "Kismet/KismetSystemLibrary.h"

使用UKismetStringLibrary::Conv_FloatToString需要添加

#include "Kismet/KismetStringLibrary.h"