根據UE4官方文檔的編程快速入門,通過編寫C++代碼,在場景中創建一個旋轉的立方體。
該立方體通過一個C++類來實現,該類繼承自父類Actor,Actor類似於Unity的prefab,可以拖到場景中。通過設置public變量,可以實現類似在unity運行時,修改gameobject的public參數的結果。
一、項目設置
選擇blank模板:
選擇C++:
創建新C++類,File–> New C++ Class…
父類選擇 Actor:
將Actor命名爲 FloatingActor,然後點擊 Create Class。:
點擊create Class後,將切換到Visual Studio並編輯代碼。
二、編寫代碼
FloatingActor.h新增代碼如下:
UCLASS()
class UE4_CPP_TEST_API AFloatingActor : public AActor
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "FloatingActor")
float FloatSpeed = 20.0f;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "FloatingActor")
float RotationSpeed = 20.0f;
// Sets default values for this actor's properties
AFloatingActor();
UPROPERTY(VisibleAnywhere)
UStaticMeshComponent* VisualMesh;
protected:
...
public:
...
};
FloatingActor.cpp新增代碼如下:
構造函數:
// Sets default values
AFloatingActor::AFloatingActor()
{
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));
}
// 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;
}
Tick()函數:
// Called every frame
void AFloatingActor::Tick(float 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的角度
NewRotation.Yaw += DeltaRotation;
SetActorLocationAndRotation(NewLocation, NewRotation);
Super::Tick(DeltaTime);
}
三、編譯C++代碼
法一:visual studio中編譯
法二:編輯器內編譯
四、放置Actor
將actor拖到視口,將Actor的 Location設置爲(-180、0、180)。:
五、運行結果
運行時調節Rotation Speed的效果:
參考資料:
https://docs.unrealengine.com/zh-CN/Programming/QuickStart/index.html