Files
MxValheim/MxValheim/Patch/HUD/Clock.cs
2026-02-11 22:44:05 -05:00

97 lines
3.6 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;
namespace MxValheim.Patch.HUD
{
internal class Clock
{
public static GameObject m_canvasObject;
public static Text m_textComponent;
// This replaces the missing GetTimeString() method
public string GetFormattedTime()
{
// Get fractional day (0.0 to 1.0)
float fraction = EnvMan.instance.GetDayFraction();
// Convert to hours and minutes
float totalHours = fraction * 24f;
int hours = Mathf.FloorToInt(totalHours);
int minutes = Mathf.FloorToInt((totalHours - hours) * 60f);
return $"{hours:00}:{minutes:00}";
}
public void CreateOverlay()
{
// 1. Root Canvas
m_canvasObject = new GameObject("ModdedCanvas");
Canvas canvas = m_canvasObject.AddComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
canvas.sortingOrder = 999;
// 2. Background Panel
GameObject panelObj = new GameObject("TextBackground");
panelObj.transform.SetParent(m_canvasObject.transform, false);
Image panelImage = panelObj.AddComponent<Image>();
panelImage.color = new Color(0, 0, 0, 0.5f); // 50% transparent black
RectTransform panelRect = panelObj.GetComponent<RectTransform>();
panelRect.anchorMin = new Vector2(0.5f, 1.0f); // Top Center
panelRect.anchorMax = new Vector2(0.5f, 1.0f);
panelRect.pivot = new Vector2(0.5f, 1.0f);
panelRect.anchoredPosition = new Vector2(0, -5); // 5px gap from top
panelRect.sizeDelta = new Vector2(180, 35); // Width and Height of the bar
// 3. Text (Attached to Panel)
GameObject textObj = new GameObject("ModdedText");
textObj.transform.SetParent(panelObj.transform, false);
m_textComponent = textObj.AddComponent<Text>();
// Attempt to find Valheim's specific font, fallback to Arial if not found
Font valheimFont = null;
foreach (Font f in Resources.FindObjectsOfTypeAll<Font>())
{
if (f.name == "AveriaSerifLibre-Bold")
{
valheimFont = f;
break;
}
}
// Corrected fallback for older Unity versions used in Valheim
if (valheimFont == null)
{
valheimFont = Resources.GetBuiltinResource<Font>("Arial.ttf");
}
m_textComponent.font = valheimFont;
m_textComponent.fontSize = 18;
m_textComponent.color = Color.white;
m_textComponent.alignment = TextAnchor.MiddleCenter;
m_textComponent.supportRichText = true;
// Add Shadow so it's visible in snow
var shadow = textObj.AddComponent<Shadow>();
shadow.effectColor = Color.black;
shadow.effectDistance = new Vector2(2, 2);
// FIX: Correct way to make text fill the parent panel
RectTransform textRect = textObj.GetComponent<RectTransform>();
textRect.anchorMin = Vector2.zero; // (0, 0)
textRect.anchorMax = Vector2.one; // (1, 1)
textRect.pivot = new Vector2(0.5f, 0.5f);
// Resetting these to zero ensures the text box matches the panel exactly
textRect.offsetMin = Vector2.zero;
textRect.offsetMax = Vector2.zero;
}
}
}