.
This commit is contained in:
54
DoomDeathmatch/src/Component/UI/TextAlignComponent.cs
Normal file
54
DoomDeathmatch/src/Component/UI/TextAlignComponent.cs
Normal file
@@ -0,0 +1,54 @@
|
||||
using Engine.Scene.Component.BuiltIn.Renderer;
|
||||
using OpenTK.Mathematics;
|
||||
|
||||
namespace DoomDeathmatch.Component.UI;
|
||||
|
||||
public class TextAlignComponent : Engine.Scene.Component.Component
|
||||
{
|
||||
public Align Alignment { get; set; } = Align.Left;
|
||||
|
||||
private TextRenderer _textRenderer = null!;
|
||||
|
||||
private string? _cachedText;
|
||||
|
||||
public override void Awake()
|
||||
{
|
||||
_textRenderer = GameObject.GetComponent<TextRenderer>()!;
|
||||
}
|
||||
|
||||
public override void Update(double parDeltaTime)
|
||||
{
|
||||
if (_textRenderer.Text == null)
|
||||
return;
|
||||
|
||||
if (_cachedText == _textRenderer.Text)
|
||||
return;
|
||||
|
||||
_cachedText = _textRenderer.Text;
|
||||
var font = _textRenderer.Font;
|
||||
var size = font.Measure(_textRenderer.Text);
|
||||
var scale = GameObject.Transform.FullTransformMatrix.ExtractScale();
|
||||
var offset = GetOffset(size) + new Vector2(0, font.Metadata.Metrics.LineHeight - font.Metadata.Metrics.Ascender) / 2;
|
||||
offset *= scale.Xy;
|
||||
|
||||
GameObject.Transform.Translation.Xy = offset;
|
||||
}
|
||||
|
||||
public Vector2 GetOffset(Vector2 parSize)
|
||||
{
|
||||
return Alignment switch
|
||||
{
|
||||
Align.Left => new Vector2(0, -parSize.Y / 2),
|
||||
Align.Center => new Vector2(-parSize.X / 2, -parSize.Y / 2),
|
||||
Align.Right => new Vector2(-parSize.X, -parSize.Y / 2),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(Alignment), Alignment, null)
|
||||
};
|
||||
}
|
||||
|
||||
public enum Align
|
||||
{
|
||||
Left,
|
||||
Center,
|
||||
Right
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user