LoginSignup
8
5

More than 5 years have passed since last update.

[UE4] UDebugDrawService による2Dデバッグ描画 (C++)

Last updated at Posted at 2018-12-15

概要

C++ で2Dのデバッグ描画を行うサンプルです。
UDebugDrawService の機能を利用しています。

↓のスクリーンショットの 赤字や青と緑のライン、薄い白の四角の表示部分です。
image.png

手順

デリゲートを作成して登録。指定した関数が毎フレーム呼ばれます。

auto drawDebugDelegate = FDebugDrawDelegate::CreateUObject(this, &ADebugDraw2dSampleGameModeBase::Draw);
if (drawDebugDelegate.IsBound())
{
    this->DrawDebugDelegateHandle = UDebugDrawService::Register(TEXT("GameplayDebug"), drawDebugDelegate);
}

登録した描画関数は UCanvas が渡ってくるので、これに対して描画コマンドを登録します。

// 呼び出される描画関数.
void ADebugDraw2dSampleGameModeBase::Draw(UCanvas* InCanvas, APlayerController* InPC)
{
    // font 描画.
    {
        FCanvasTextItem item(FVector2D(32.0f, 64.0f), FText::FromString(TEXT("abcdefg")), this->FontObject, FLinearColor::Red);
        InCanvas->DrawItem(item);
    }

    // line 描画.
    {
        FCanvasLineItem item(FVector2D(28.0f, 110.0f), FVector2D(90.0f, 110.0f));
        item.SetColor(FLinearColor::Blue);
        InCanvas->DrawItem(item);
    }
}

フォント描画を行う場合、UFont が必要です。
↓はコンストラクタで事前にロードする例。

ADebugDraw2dSampleGameModeBase::ADebugDraw2dSampleGameModeBase()
{
    static ConstructorHelpers::FObjectFinder<UFont> font(TEXT("/Engine/EngineFonts/Roboto"));
    FontObject = font.Object;
}

終了時は、登録したデリゲートを解除します。

if (this->DrawDebugDelegateHandle.IsValid())
{
    UDebugDrawService::Unregister(this->DrawDebugDelegateHandle);
    this->DrawDebugDelegateHandle.Reset();
}

font と Line 以外にも Tile / Box / Triangle 等あるのが CanvasItem.h を見ればわかります。

サンプルプロジェクト

このサンプルプロジェクトのコードでは GameMode 上で実装していますが、Actor派生でもComponent派生でも組み込めると思います。

動作確認環境

UnrealEngine 4.21.1
Visual Studio Community 2015

最後に

3Dのデバッグ描画は、DrawDebugHelpers.h にある DrawDebugLine や DrawDebugString があるのがすぐに見つかりました。

DrawDebugHelpers.h
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);
ENGINE_API void DrawDebugString(const UWorld* InWorld, FVector const& TextLocation, const FString& Text, class AActor* TestBaseActor = NULL, FColor const& TextColor = FColor::White, float Duration = -1.000000, bool bDrawShadow = false, float FontScale = 1.f);
ENGINE_API void DrawDebugSphere(const UWorld* InWorld, FVector const& Center, float Radius, int32 Segments, FColor const& Color, bool bPersistentLines = false, float LifeTime=-1.f, uint8 DepthPriority = 0, float Thickness = 0.f);

しかし、C++ のみで簡単に実現する2Dでのデバッグ描画はあまり情報がなく、この手法を知る前は、UMG の Widget を C++ 上で作成してそれに描画とかしていました。
UDebugDrawService を利用する方がかなりシンプルになります。

しかし、あくまでデバッグ用の描画なので、Shipping や Test ビルドなどでは無効になるようにしておくのが良いかと思います。

8
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
5