UE4的藍圖內有各種方便的Debug繪製功能,在此整理在C++中使用的快速繪製Debug圖形方法。
2D繪製:使用UDebugDrawService
此處以某攝影機的Actor為例子。 在Class內追加FDelegateHandleCameraDebugDrawHandle。 之後將它登錄到UDebugDrawService。登錄後每個Frame會呼叫此登錄的函數。 在函數傳入值的Canvas上直接繪製需要的圖形。
(TestCamera.h) class ATestCamera : public AActor { GENERATED_BODY() public: ASideScrollTestCamera(); void DebugDraw(UCanvas* InCanvas, APlayerController* InPC); protected: FDelegateHandle CameraDebugDrawHandle; };
(TestCamera.cpp) #include "TestCamera.h" #include "Debug/DebugDrawService.h" ASideScrollTestCamera::ATestCamera() { FDebugDrawDelegate DrawDebugDelegate = FDebugDrawDelegate::CreateUObject(this, &TestCamera::HandleDebugDraw); CameraDebugDrawHandle = UDebugDrawService::Register(TEXT("GameplayDebug"), DrawDebugDelegate); } void ANxPlayerCameraManager::BeginDestroy() { Super::BeginDestroy(); // 物件刪除時解除登錄 UDebugDrawService::Unregister(this->DrawDebugDelegateHandle); } void ASideScrollTestCamera::HandleDebugDraw(UCanvas* InCanvas, APlayerController* InPC) { // 在此繪製Debug圖形 FCanvasLineItem item(FVector2D(100.f, 100.0f), FVector2D(200.f, 200.0f)); item.LineThickness = 10.f; item.SetColor(FLinearColor::Red); InCanvas->DrawItem(item); }
3D繪製:使用DrawDebugHelpers
請參照引擎原始碼的DrawDebugHelpers.h的DrawDebugLine等,include後直接使用即可。
/** Draw a debug line */ ENGINE_API void DrawDebugLine(const UWorld* InWorld, FVector const& LineStart, FVector const& LineEnd, FColor const& Color, bool bPersistentLines = false, float LifeTime=-1.f, uint8 DepthPriority = 0, float Thickness = 0.f); /** Draw a debug point */ ENGINE_API void DrawDebugPoint(const UWorld* InWorld, FVector const& Position, float Size, FColor const& PointColor, bool bPersistentLines = false, float LifeTime=-1.f, uint8 DepthPriority = 0); /** Draw directional arrow **/ ENGINE_API void DrawDebugDirectionalArrow(const UWorld* InWorld, FVector const& LineStart, FVector const& LineEnd, float ArrowSize, FColor const& Color, bool bPersistentLines = false, float LifeTime=-1.f, uint8 DepthPriority = 0, float Thickness = 0.f);
其實這篇主要是想提2D繪製。之前還要特別製作Widget來繪製,之後才發現有這個方便的功能,讓繪製的流程快速多了。