本文旨在解决因UI问题导致屏幕中心位置不对的问题
处理前的现象:如果四周UI透明度都为1,那么方块的位置就不太对,没在中心
处理后的现象:
解决办法:自定义大小和视口偏移
创建一个基于子系统的类或者蓝图函数库(什么类不重要,你调的到就行)
.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Subsystems/GameInstanceSubsystem.h"
#include "CustomGameViewSizeSub.generated.h"
/**
*
*/
class FViewport;
//定义当视口大小发生变化时的代理
DECLARE_DYNAMIC_MULTICAST_DELEGATE(FOnViewportResized);
UCLASS()
class CUSTOMGAMEVIEWSIZE_API UCustomGameViewSizeSub : public UGameInstanceSubsystem
{
GENERATED_BODY()
public:
UPROPERTY(BlueprintAssignable, Category = "Delegate")
FOnViewportResized OnViewportResized;
public:
void ViewportResize(FViewport* Viewport, uint32 Size);
virtual void Initialize(FSubsystemCollectionBase& Collection) override;
UFUNCTION(BlueprintCallable, Category = "Fun Tool")
void AdjustViewportSize(FMargin margin);
};
.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "CustomGameViewSizeSub.h"
#include "UnrealClient.h"
#include "Engine/Engine.h"
#include "Engine/GameViewportClient.h"
void UCustomGameViewSizeSub::Initialize(FSubsystemCollectionBase& Collection)
{
GEngine->GameViewport->Viewport->ViewportResizedEvent.AddUObject(this, &UCustomGameViewSizeSub::ViewportResize);
}
void UCustomGameViewSizeSub::ViewportResize(FViewport* Viewport, uint32 Size)
{
OnViewportResized.Broadcast();
}
void UCustomGameViewSizeSub::AdjustViewportSize(FMargin margin)
{
UE_LOG(LogTemp, Log, TEXT(" AdjustViewportSize "));
if (GEngine->GameViewport)
{
FVector2D ViewportSize;
GEngine->GameViewport->GetViewportSize(ViewportSize);
if (ViewportSize.X > 0 && ViewportSize.Y > 0)
{
//视口大小缩放
GEngine->GameViewport->SplitscreenInfo[0].PlayerData[0].SizeX = margin.Right / ViewportSize.X;
GEngine->GameViewport->SplitscreenInfo[0].PlayerData[0].SizeY = margin.Bottom / ViewportSize.Y;
//基于视口原点偏移,原点是左上角(0,0)
GEngine->GameViewport->SplitscreenInfo[0].PlayerData[0].OriginX = margin.Left / ViewportSize.X;
GEngine->GameViewport->SplitscreenInfo[0].PlayerData[0].OriginY = margin.Top / ViewportSize.Y;
}
}
}
UMG设计图:
逻辑实现:
最终效果: