文章目錄
- 實際需求
- 1.頭文件
- 2.源文件
- 3.用法
- 小結
實際需求
這個需求來源于之前的一個項目,當時用了一個第三方插件,里邊有一些繪制線段的代碼,c++層用的是drawdebugline,當時看底層,覺得應該沒問題,不應該在release上跑不起來,由于種種原因,沒有時間去搞這塊,后來丟給其他同事,也解決了,但是沒有按照我的思路來。
最近在玩各種ai工具,覺得有點意思,就去解決點實際問題,就拿當時的問題練練手。
1.頭文件
#pragma once#include "Kismet/BlueprintFunctionLibrary.h"
#include "RuntimeLineDrawer.generated.h"UCLASS()
class YOURMODULE_API URuntimeLineDrawer : public UBlueprintFunctionLibrary
{GENERATED_BODY()public:/** 在運行時(含Shipping)繪制一條線 */UFUNCTION(BlueprintCallable, Category="RuntimeDraw")static void DrawLineRuntime(UObject* WorldContextObject,FVector Start,FVector End,FLinearColor Color = FLinearColor::Red,float Thickness = 2.f,float LifeTime = 0.f,bool bDepthTest = true);
};
2.源文件
#include "RuntimeLineDrawer.h"
#include "Engine/World.h"
#include "Engine/Engine.h"
#include "Components/LineBatchComponent.h"
#include "Engine/EngineTypes.h" // SDPG_World, SDPG_Foregroundvoid URuntimeLineDrawer::DrawLineRuntime(UObject* WorldContextObject,FVector Start,FVector End,FLinearColor Color,float Thickness,float LifeTime,bool bDepthTest
)
{if (!WorldContextObject) return;UWorld* World = WorldContextObject->GetWorld();if (!World) return;// 確保世界里有一個持久的 LineBatcher(發布版也可用)ULineBatchComponent* LineBatcher = World->PersistentLineBatcher;if (!LineBatcher){LineBatcher = NewObject<ULineBatchComponent>(World);LineBatcher->RegisterComponentWithWorld(World);World->PersistentLineBatcher = LineBatcher;}// 構建一條線(FBatchedLine)// DepthPriority: 0=SDPG_World, 1=SDPG_Foregroundconst uint8 DepthPriority = bDepthTest ? (uint8)SDPG_World : (uint8)SDPG_Foreground;TArray<FBatchedLine> Lines;Lines.Emplace(Start, End, Color, Thickness, LifeTime, DepthPriority);LineBatcher->DrawLines(Lines);LineBatcher->MarkRenderStateDirty(); // 提示渲染更新
}
3.用法
URuntimeLineDrawer::DrawLineRuntime(this, FVector(0,0,100), FVector(100,0,100),FLinearColor::Green, 3.f, /*LifeTime*/2.f, /*bDepthTest*/true);
小結
這只是個例子,完整的代碼托管在完整代碼,可以看下目錄結構,如下:
YourProject/
└─ Plugins/└─ RuntimeLineDraw/├─ RuntimeLineDraw.uplugin└─ Source/└─ RuntimeLineDraw/├─ RuntimeLineDraw.Build.cs├─ Public/│ └─ RuntimeLineDrawer.h└─ Private/├─ RuntimeLineDrawer.cpp└─ RuntimeLineDrawModule.cpp
有興趣可以去看看我這是以插件的形式給出的,具體,可以參考上圖放到你自己的項目工程中。