为actor添加一个静态网格体组件变量,类型是public的
UPROPERTY(VisibleAnywhere) //这样才能让虚幻编辑器看到这个变量(公开)
UStaticMeshComponent* VisualMesh;//StaticMeshComponent,它将担当对象的视觉表示
在构造函数里,我们对指针变量进行赋值。
//创建一个组件,并将该组件的地址赋给指针变量
VisualMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));
//将该组件附属在根组件上面
VisualMesh->SetupAttachment(RootComponent);
在这里我们看一下CreateDefaultSubobject的代码
//这是一个模板类,并且返回一个指针
template<class TReturnType>
TReturnType* CreateDefaultSubobject(FName SubobjectName, bool bTransient = false)
{
UClass* ReturnType = TReturnType::StaticClass();
return static_cast<TReturnType*>(CreateDefaultSubobject(SubobjectName, ReturnType, ReturnType, /*bIsRequired =*/ true, bTransient));
}
现在在资源文件夹下,找到相关资源
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));
}
在tick()函数中,写功能,希望actor可以自转和上下浮动
//获得actor的位置
FVector NewLocation = GetActorLocation();
//获得actor的旋转角度
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
//得到绕z轴的旋转角度
NewRotation.Yaw += DeltaRotation;
//设置高度和旋转角度
SetActorLocationAndRotation(NewLocation, NewRotation);
编译,然后创建蓝图
测试成功。