Files
Perekyp-2.0/Assets/Scripts/Player/Tools/ToolRadialMenu.cs
T
2026-11-19 23:24:44 +03:00

185 lines
7.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Радиальное меню инструментов (удерживать Tab, выбрать мышью, отпустить).
/// Рисуется через OnGUI, поэтому работает для любого количества инструментов
/// (руки, зачистка, шпатель, наждачка, баллончик, ключ, мойка Керхер, толщиномер, OBD-сканер).
/// Колесо мыши и клавиши 1–9 — быстрый выбор.
/// </summary>
public class ToolRadialMenu : MonoBehaviour
{
[Header("Ссылки")]
[Tooltip("Старая панель uGUI (скрывается — меню рисуется процедурно)")]
[SerializeField] private GameObject menuPanel;
[SerializeField] private PlayerToolManager toolManager;
[SerializeField] private Image[] sectorIcons;
[Header("Цвета выделения")]
[SerializeField] private Color normalColor = Color.white;
[SerializeField] private Color selectedColor = Color.yellow;
private int selectedIndex = 0;
private bool isMenuOpen = false;
private readonly List<ToolType> tools = new List<ToolType>();
private static readonly string[] Icons = { "Р", "З", "Ш", "Н", "Б", "К", "М", "Т", "OBD" };
private void Start()
{
if (menuPanel != null) menuPanel.SetActive(false);
if (toolManager == null) toolManager = FindAnyObjectByType<PlayerToolManager>();
}
private void RebuildToolList()
{
tools.Clear();
bool diploma = GameEconomyManager.Instance == null || GameEconomyManager.Instance.DiplomaFeatures;
foreach (ToolType t in System.Enum.GetValues(typeof(ToolType)))
{
if (!diploma && PlayerToolManager.IsDiplomaTool(t)) continue;
tools.Add(t);
}
}
private void Update()
{
if (toolManager == null) toolManager = FindAnyObjectByType<PlayerToolManager>();
if (toolManager == null || !toolManager.isActiveAndEnabled) return;
bool otherWindowOpen = GameInputLock.IsLockedByOther(this);
// Открытие/закрытие по клавише Tab
if (Input.GetKeyDown(KeyCode.Tab) && !otherWindowOpen)
{
OpenMenu();
}
else if (isMenuOpen && (Input.GetKeyUp(KeyCode.Tab) || otherWindowOpen))
{
CloseMenuAndApply();
}
if (isMenuOpen)
{
CalculateMouseSector();
return;
}
if (otherWindowOpen) return;
// Быстрый выбор: колесо мыши и цифры
if (tools.Count == 0) RebuildToolList();
float wheel = Input.mouseScrollDelta.y;
if (Mathf.Abs(wheel) > 0.01f && tools.Count > 0)
{
int cur = Mathf.Max(0, tools.IndexOf(toolManager.currentTool));
int next = (cur + (wheel < 0 ? 1 : -1) + tools.Count) % tools.Count;
toolManager.SelectTool(tools[next]);
}
for (int i = 0; i < Mathf.Min(9, tools.Count); i++)
{
if (Input.GetKeyDown(KeyCode.Alpha1 + i))
toolManager.SelectTool(tools[i]);
}
}
private void OpenMenu()
{
RebuildToolList();
isMenuOpen = true;
selectedIndex = Mathf.Max(0, tools.IndexOf(toolManager.currentTool));
GameInputLock.Lock(this);
}
private void CalculateMouseSector()
{
if (tools.Count == 0) return;
Vector2 screenCenter = new Vector2(Screen.width * 0.5f, Screen.height * 0.5f);
Vector2 mouseDelta = (Vector2)Input.mousePosition - screenCenter;
// Если мышь почти в центре - ничего не меняем
if (mouseDelta.magnitude < 40f * GameUI.Scale) return;
// Угол от верхней точки по часовой стрелке
float angle = Mathf.Atan2(mouseDelta.x, mouseDelta.y) * Mathf.Rad2Deg;
if (angle < 0) angle += 360f;
float sectorSize = 360f / tools.Count;
selectedIndex = Mathf.Clamp(Mathf.FloorToInt((angle + sectorSize * 0.5f) % 360f / sectorSize), 0, tools.Count - 1);
}
private void CloseMenuAndApply()
{
isMenuOpen = false;
GameInputLock.Unlock(this);
if (tools.Count > 0 && selectedIndex < tools.Count && tools[selectedIndex] != toolManager.currentTool)
toolManager.SelectTool(tools[selectedIndex]);
}
private void OnDisable()
{
if (isMenuOpen)
{
isMenuOpen = false;
GameInputLock.Unlock(this);
}
}
private void OnGUI()
{
if (!isMenuOpen || tools.Count == 0) return;
GameUI.Begin(-5);
float cx = GameUI.VirtualWidth * 0.5f;
float cy = GameUI.VirtualHeight * 0.5f;
float radius = 250f;
GUI.DrawTexture(new Rect(cx - radius - 90, cy - radius - 90, (radius + 90) * 2, (radius + 90) * 2),
GameUI.Rounded(GameUI.Bg.WithAlpha(0.72f), null, 60, 0));
GUI.Label(new Rect(cx - 160, cy - 40, 320, 40), "ИНСТРУМЕНТЫ", GameUI.Header.WithCenter());
if (selectedIndex < tools.Count)
GUI.Label(new Rect(cx - 170, cy, 340, 60), PlayerToolManager.GetToolName(tools[selectedIndex]), GameUI.LabelCenter);
for (int i = 0; i < tools.Count; i++)
{
float a = (360f / tools.Count) * i * Mathf.Deg2Rad;
Vector2 p = new Vector2(cx + Mathf.Sin(a) * radius, cy - Mathf.Cos(a) * radius);
bool sel = i == selectedIndex;
float size = sel ? 128f : 108f;
Rect r = new Rect(p.x - size * 0.5f, p.y - size * 0.5f, size, size);
Color fill = sel ? GameUI.Accent : GameUI.PanelLight;
GUI.DrawTexture(r, GameUI.Rounded(fill, sel ? Color.white : GameUI.Hex("3A3F4A"), 18, 2));
int idx = (int)tools[i];
string icon = idx < Icons.Length ? Icons[idx] : "•";
GUIStyle st = new GUIStyle(GameUI.LabelCenter) { fontSize = sel ? 34 : 30, normal = { textColor = sel ? GameUI.Bg : GameUI.TextColor } };
GUI.Label(new Rect(r.x, r.y + 6, r.width, r.height * 0.55f), icon, st);
GUIStyle sm = new GUIStyle(GameUI.SmallCenter) { fontSize = 13, wordWrap = true, normal = { textColor = sel ? GameUI.Bg : GameUI.Muted } };
GUI.Label(new Rect(r.x + 4, r.y + r.height * 0.55f, r.width - 8, r.height * 0.42f), $"{i + 1}. {ShortName(tools[i])}", sm);
}
}
private static string ShortName(ToolType t)
{
switch (t)
{
case ToolType.Hands: return "Руки";
case ToolType.RustCleaner: return "Зачистка";
case ToolType.Putty: return "Шпатель";
case ToolType.Sander: return "Наждачка";
case ToolType.SprayCan: return "Баллончик";
case ToolType.Wrench: return "Ключ";
case ToolType.PressureWasher: return "Мойка";
case ToolType.ThicknessGauge: return "Толщиномер";
case ToolType.OBDScanner: return "OBD-сканер";
default: return t.ToString();
}
}
}