Handbuch Tabs: Bauen und Index (fertig)
UI_Prefabs HandbuchDataAssets
This commit is contained in:
@@ -0,0 +1,103 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
|
||||
namespace DepthsOfGreed.HandbookUI
|
||||
{
|
||||
public sealed class BuildMenuController : MonoBehaviour
|
||||
{
|
||||
public TestPlacementController Placement { get; set; }
|
||||
private readonly List<TowerCardView> cards = new List<TowerCardView>();
|
||||
private Button[] categories;
|
||||
private int selectedCategory = -1;
|
||||
private TowerCardView revealed;
|
||||
private HandbookTowerEntry[][] entries;
|
||||
|
||||
public void Initialize(HandbookTowerCatalog catalog)
|
||||
{
|
||||
categories = new[] {
|
||||
transform.Find("LeftPage/CategoryBar/Category_Ammo").GetComponent<Button>(),
|
||||
transform.Find("LeftPage/CategoryBar/Category_Energy").GetComponent<Button>(),
|
||||
transform.Find("LeftPage/CategoryBar/Category_Special").GetComponent<Button>()
|
||||
};
|
||||
var left = transform.Find("LeftPage/Cards_Left");
|
||||
var right = transform.Find("RightPage/Cards_Right");
|
||||
int count = Mathf.Max(left.childCount, right.childCount);
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
if (i < left.childCount) AddCard(left.GetChild(i));
|
||||
if (i < right.childCount) AddCard(right.GetChild(i));
|
||||
}
|
||||
var groups = new[] { new List<HandbookTowerEntry>(), new List<HandbookTowerEntry>(), new List<HandbookTowerEntry>() };
|
||||
if (catalog && catalog.towers != null)
|
||||
foreach (var entry in catalog.towers)
|
||||
if (entry) groups[(int)entry.category].Add(entry);
|
||||
entries = new[] { groups[0].ToArray(), groups[1].ToArray(), groups[2].ToArray() };
|
||||
foreach (var group in groups)
|
||||
if (group.Count > cards.Count)
|
||||
Debug.LogWarning("Handbuch: Mehr Turmtypen als Kartenplätze in einer Kategorie.", this);
|
||||
for (int i = 0; i < categories.Length; i++)
|
||||
{
|
||||
int index = i;
|
||||
categories[i].onClick.AddListener(() => SelectCategory(index));
|
||||
}
|
||||
SelectCategory(0);
|
||||
}
|
||||
|
||||
private void AddCard(Transform card)
|
||||
{
|
||||
var view = card.gameObject.AddComponent<TowerCardView>();
|
||||
view.Initialize(this);
|
||||
cards.Add(view);
|
||||
}
|
||||
|
||||
public void SelectCategory(int index)
|
||||
{
|
||||
if (index == selectedCategory) return;
|
||||
selectedCategory = index;
|
||||
revealed = null;
|
||||
for (int i = 0; i < cards.Count; i++)
|
||||
{
|
||||
cards[i].SetBack(false, true);
|
||||
bool visible = i < entries[index].Length;
|
||||
cards[i].gameObject.SetActive(visible);
|
||||
if (visible) cards[i].Bind(entries[index][i]);
|
||||
}
|
||||
for (int i = 0; i < categories.Length; i++)
|
||||
{
|
||||
var colors = categories[i].colors;
|
||||
colors.normalColor = i == index ? new Color(1f, 0.72f, 0.2f) : new Color(0.82f, 0.82f, 0.82f);
|
||||
colors.highlightedColor = i == index ? new Color(1f, 0.82f, 0.4f) : Color.white;
|
||||
colors.selectedColor = colors.normalColor;
|
||||
colors.pressedColor = new Color(0.7f, 0.7f, 0.7f);
|
||||
categories[i].colors = colors;
|
||||
categories[i].image.color = Color.white;
|
||||
}
|
||||
}
|
||||
|
||||
public void ToggleCard(TowerCardView card)
|
||||
{
|
||||
if (revealed == card)
|
||||
{
|
||||
card.SetBack(false);
|
||||
revealed = null;
|
||||
return;
|
||||
}
|
||||
if (revealed) revealed.SetBack(false);
|
||||
revealed = card;
|
||||
card.SetBack(true);
|
||||
}
|
||||
|
||||
public void ResetCards()
|
||||
{
|
||||
revealed = null;
|
||||
foreach (var card in cards) card.SetBack(false, true);
|
||||
}
|
||||
|
||||
public void ResetForClose()
|
||||
{
|
||||
ResetCards();
|
||||
SelectCategory(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b92a68cbefa40444dbf1b9b6dbb3f1a1
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 1aa70cdb86ec7c94db08b483177bafb4
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,242 @@
|
||||
using System;
|
||||
using UnityEditor;
|
||||
using UnityEditor.SceneManagement;
|
||||
using UnityEngine;
|
||||
|
||||
[InitializeOnLoad]
|
||||
public static class HandbookSceneValidation
|
||||
{
|
||||
public static void ConfigureFeedbackAndValidate()
|
||||
{
|
||||
try
|
||||
{
|
||||
var scene = EditorSceneManager.OpenScene("Assets/Scenes/Tim_Test_UI.unity");
|
||||
var controller = UnityEngine.Object.FindFirstObjectByType<DepthsOfGreed.HandbookUI.HandbookController>(FindObjectsInactive.Include);
|
||||
var serialized = new SerializedObject(controller);
|
||||
serialized.FindProperty("successfulPlacementDelay").floatValue = 0.5f;
|
||||
serialized.ApplyModifiedPropertiesWithoutUndo();
|
||||
EditorSceneManager.SaveScene(scene);
|
||||
Validate();
|
||||
}
|
||||
catch (Exception e) { Debug.LogException(e); EditorApplication.Exit(1); }
|
||||
}
|
||||
public static void SetupAndValidate()
|
||||
{
|
||||
try
|
||||
{
|
||||
const string dataFolder = "Assets/HandbookData";
|
||||
const string towerFolder = dataFolder + "/TestTowers";
|
||||
if (!AssetDatabase.IsValidFolder(dataFolder)) AssetDatabase.CreateFolder("Assets", "HandbookData");
|
||||
if (!AssetDatabase.IsValidFolder(towerFolder)) AssetDatabase.CreateFolder(dataFolder, "TestTowers");
|
||||
var names = new[] {
|
||||
new[] { "Gewehr", "Minigun", "Sniper", "Granatenwerfer", "Howitzer", "Flammenwerfer" },
|
||||
new[] { "Laser-Piercer", "Bouncer", "Pusher", "Knocker", "Laser-Beam" },
|
||||
new[] { "Falle", "Generator", "Staubsauger", "Spiegel" }
|
||||
};
|
||||
var prefixes = new[] { "ammo", "energy", "special" };
|
||||
var entries = new System.Collections.Generic.List<DepthsOfGreed.HandbookUI.HandbookTowerEntry>();
|
||||
for (int category = 0; category < names.Length; category++)
|
||||
for (int i = 0; i < names[category].Length; i++)
|
||||
{
|
||||
string path = towerFolder + "/" + prefixes[category] + "_" + i + "_" + names[category][i] + ".asset";
|
||||
var entry = AssetDatabase.LoadAssetAtPath<DepthsOfGreed.HandbookUI.HandbookTowerEntry>(path);
|
||||
if (!entry)
|
||||
{
|
||||
entry = ScriptableObject.CreateInstance<DepthsOfGreed.HandbookUI.HandbookTowerEntry>();
|
||||
entry.id = prefixes[category] + "_" + i;
|
||||
entry.displayName = names[category][i];
|
||||
entry.category = (DepthsOfGreed.HandbookUI.HandbookTowerCategory)category;
|
||||
entry.energyCost = 100 + i * 25;
|
||||
entry.summary = category == 0 ? "Schaden: 20 · Schüsse/s: 2" : category == 1 ? "Energieverbrauch: 5/s" :
|
||||
new[] { "Falle · Testwirkung", "Energieerzeugung · Testwert: 5/s", "Sammelfunktion · Testeintrag", "Umlenkung · Testeintrag" }[i];
|
||||
entry.description = entry.displayName + " – Testeintrag\n\nHier steht später eine kurze Erklärung der Funktion. Kosten und Werte sind vorläufige Testdaten.\n\nKlicken: zurück zur Baukarte";
|
||||
AssetDatabase.CreateAsset(entry, path);
|
||||
}
|
||||
entries.Add(entry);
|
||||
}
|
||||
const string catalogPath = dataFolder + "/TestTurmkatalog.asset";
|
||||
var catalog = AssetDatabase.LoadAssetAtPath<DepthsOfGreed.HandbookUI.HandbookTowerCatalog>(catalogPath);
|
||||
if (!catalog)
|
||||
{
|
||||
catalog = ScriptableObject.CreateInstance<DepthsOfGreed.HandbookUI.HandbookTowerCatalog>();
|
||||
catalog.towers = entries.ToArray();
|
||||
AssetDatabase.CreateAsset(catalog, catalogPath);
|
||||
}
|
||||
AssetDatabase.SaveAssets();
|
||||
var scene = EditorSceneManager.OpenScene("Assets/Scenes/Tim_Test_UI.unity");
|
||||
catalog = AssetDatabase.LoadAssetAtPath<DepthsOfGreed.HandbookUI.HandbookTowerCatalog>(catalogPath);
|
||||
if (!catalog) throw new Exception("Catalog asset could not be loaded after scene switch.");
|
||||
var controller = UnityEngine.Object.FindFirstObjectByType<DepthsOfGreed.HandbookUI.HandbookController>(FindObjectsInactive.Include);
|
||||
var serialized = new SerializedObject(controller);
|
||||
serialized.FindProperty("towerCatalog").objectReferenceValue = catalog;
|
||||
serialized.FindProperty("successfulPlacementDelay").floatValue = 1f;
|
||||
serialized.ApplyModifiedPropertiesWithoutUndo();
|
||||
EditorSceneManager.SaveScene(scene);
|
||||
Debug.Log("HANDBOOK_DATA_SETUP_OK: 15 editable tower assets and catalog connected; delay set to 1 second.");
|
||||
Validate();
|
||||
}
|
||||
catch (Exception exception) { Debug.LogException(exception); EditorApplication.Exit(1); }
|
||||
}
|
||||
static HandbookSceneValidation()
|
||||
{
|
||||
if (SessionState.GetBool("HandbookValidationPending", false))
|
||||
EditorApplication.playModeStateChanged += CheckPlayMode;
|
||||
}
|
||||
public static void Validate()
|
||||
{
|
||||
try
|
||||
{
|
||||
var scene = EditorSceneManager.OpenScene("Assets/Scenes/Tim_Test_UI.unity");
|
||||
var controllers = UnityEngine.Object.FindObjectsByType<DepthsOfGreed.HandbookUI.HandbookController>(FindObjectsInactive.Include, FindObjectsSortMode.None);
|
||||
if (controllers.Length != 1) throw new Exception("Expected exactly one handbook controller.");
|
||||
var serialized = new SerializedObject(controllers[0]);
|
||||
foreach (var field in new[] { "closedBook", "openBook", "bookButton", "closeButton", "closedTabsRoot", "openTabsRoot", "towerCatalog", "testTowerPrefab" })
|
||||
if (!serialized.FindProperty(field).objectReferenceValue) throw new Exception("Missing reference: " + field);
|
||||
foreach (var field in new[] { "closedTabs", "openTabs", "pages" })
|
||||
{
|
||||
var array = serialized.FindProperty(field);
|
||||
if (array.arraySize != 4) throw new Exception("Invalid array: " + field);
|
||||
for (int i = 0; i < array.arraySize; i++)
|
||||
if (!array.GetArrayElementAtIndex(i).objectReferenceValue) throw new Exception("Missing array reference: " + field);
|
||||
}
|
||||
foreach (var root in scene.GetRootGameObjects())
|
||||
foreach (var transform in root.GetComponentsInChildren<Transform>(true))
|
||||
if (GameObjectUtility.GetMonoBehavioursWithMissingScriptCount(transform.gameObject) != 0)
|
||||
throw new Exception("Missing script on " + transform.name);
|
||||
Debug.Log("HANDBOOK_SCENE_VALIDATION_OK: Scene loaded; all controller references resolved; no missing scripts.");
|
||||
EditorApplication.playModeStateChanged += CheckPlayMode;
|
||||
SessionState.SetBool("HandbookValidationPending", true);
|
||||
EditorApplication.EnterPlaymode();
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Debug.LogException(exception);
|
||||
EditorApplication.Exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
private static void CheckPlayMode(PlayModeStateChange state)
|
||||
{
|
||||
if (state != PlayModeStateChange.EnteredPlayMode) return;
|
||||
SessionState.SetBool("HandbookValidationPending", false);
|
||||
EditorApplication.playModeStateChanged -= CheckPlayMode;
|
||||
try
|
||||
{
|
||||
var controller = UnityEngine.Object.FindFirstObjectByType<DepthsOfGreed.HandbookUI.HandbookController>();
|
||||
controller.Open(0);
|
||||
var menu = UnityEngine.Object.FindFirstObjectByType<DepthsOfGreed.HandbookUI.BuildMenuController>();
|
||||
if (!menu) throw new Exception("Build menu did not initialize.");
|
||||
foreach (var pair in new[] { (0, 6), (1, 5), (2, 4) })
|
||||
{
|
||||
menu.SelectCategory(pair.Item1);
|
||||
var cards = menu.GetComponentsInChildren<DepthsOfGreed.HandbookUI.TowerCardView>();
|
||||
if (cards.Length != pair.Item2) throw new Exception("Wrong category card count.");
|
||||
foreach (var card in cards)
|
||||
if (card.Entry == null || !card.transform.Find("Front").gameObject.activeSelf || card.transform.Find("Back").gameObject.activeSelf)
|
||||
throw new Exception("Invalid initial card state.");
|
||||
}
|
||||
menu.SelectCategory(0);
|
||||
var first = menu.GetComponentsInChildren<DepthsOfGreed.HandbookUI.TowerCardView>()[0];
|
||||
menu.ToggleCard(first);
|
||||
double deadline = EditorApplication.timeSinceStartup + 0.6;
|
||||
EditorApplication.CallbackFunction check = null;
|
||||
check = () => {
|
||||
if (EditorApplication.timeSinceStartup < deadline) return;
|
||||
EditorApplication.update -= check;
|
||||
try {
|
||||
if (!first.transform.Find("Back").gameObject.activeSelf) throw new Exception("Card flip did not complete.");
|
||||
menu.SelectCategory(1);
|
||||
if (first.transform.Find("Back").gameObject.activeSelf) throw new Exception("Category did not reset card.");
|
||||
controller.Close();
|
||||
controller.Open(0);
|
||||
if (menu.GetComponentsInChildren<DepthsOfGreed.HandbookUI.TowerCardView>().Length != 6)
|
||||
throw new Exception("Closing did not restore the default build category.");
|
||||
controller.Close();
|
||||
foreach (var card in menu.GetComponentsInChildren<DepthsOfGreed.HandbookUI.TowerCardView>(true))
|
||||
if (card.transform.Find("Back").gameObject.activeSelf) throw new Exception("Book close did not reset cards.");
|
||||
controller.Open(3);
|
||||
var indexMenu = UnityEngine.Object.FindFirstObjectByType<DepthsOfGreed.HandbookUI.HandbookIndexController>();
|
||||
if (!indexMenu || indexMenu.VisibleEntryCount != 15 || indexMenu.SelectedEntry != null)
|
||||
throw new Exception("Index initialization failed.");
|
||||
indexMenu.SelectEntry(0);
|
||||
if (!indexMenu.SelectedEntry) throw new Exception("Index selection failed.");
|
||||
indexMenu.ListScroll.verticalNormalizedPosition = 0f;
|
||||
controller.Open(0);
|
||||
controller.Open(3);
|
||||
if (indexMenu.SelectedEntry != null || indexMenu.ListScroll.verticalNormalizedPosition < 0.99f)
|
||||
throw new Exception("Index re-entry did not reset selection and scroll.");
|
||||
indexMenu.SelectFilter(2);
|
||||
if (indexMenu.VisibleEntryCount != 0 || indexMenu.SelectedEntry != null)
|
||||
throw new Exception("Enemy filter failed.");
|
||||
indexMenu.SelectFilter(1);
|
||||
if (indexMenu.VisibleEntryCount != 15) throw new Exception("Tower filter failed.");
|
||||
indexMenu.SelectEntry(1);
|
||||
controller.Close();
|
||||
controller.Open(3);
|
||||
if (indexMenu.SelectedEntry != null || indexMenu.ListScroll.verticalNormalizedPosition < 0.99f)
|
||||
throw new Exception("Reopening index did not reset selection and scroll.");
|
||||
controller.Close();
|
||||
var placement = controller.GetComponent<DepthsOfGreed.HandbookUI.TestPlacementController>();
|
||||
var entry = first.Entry;
|
||||
if (!placement.enabled) throw new Exception("Placement initialization failed.");
|
||||
controller.Open(0);
|
||||
var validScreen = (Vector2)Camera.main.WorldToScreenPoint(new Vector3(3.5f, 0, 0));
|
||||
if (!placement.Begin(entry, validScreen) || !placement.IsDragging) throw new Exception("Drag did not begin.");
|
||||
placement.Cancel();
|
||||
if (placement.IsDragging || placement.TowerCount != 0) throw new Exception("Cancel created a tower.");
|
||||
if (placement.TryPlaceAt(entry, Vector3.zero, out _)) throw new Exception("Center must be invalid.");
|
||||
if (placement.TryPlaceAt(entry, new Vector3(3.1f, 0, 0), out _)) throw new Exception("Base crosses inner wall.");
|
||||
if (placement.TryPlaceAt(entry, new Vector3(3.9f, 0, 0), out _)) throw new Exception("Base crosses outer wall.");
|
||||
int initialEnergy = placement.Energy;
|
||||
if (!placement.Begin(entry, validScreen)) throw new Exception("Second drag did not begin.");
|
||||
placement.End(validScreen);
|
||||
if (placement.TowerCount != 1 || placement.IsDragging) throw new Exception("Drag release failed.");
|
||||
if (!placement.IsWaitingForReturn) throw new Exception("Successful placement did not start delay.");
|
||||
for (int i = 1; i < 8; i++) {
|
||||
float angle = i * Mathf.PI / 4f;
|
||||
if (!placement.TryPlaceAt(entry, new Vector3(Mathf.Cos(angle) * 3.5f, Mathf.Sin(angle) * 3.5f, 0), out string reason))
|
||||
throw new Exception("Valid placement failed: " + reason);
|
||||
}
|
||||
if (placement.TowerCount != 8 || placement.Energy != initialEnergy - entry.energyCost * 8)
|
||||
throw new Exception("Wrong tower count or resource deduction.");
|
||||
if (placement.TryPlaceAt(entry, new Vector3(3.5f, 0, 0), out _)) throw new Exception("Overlap allowed.");
|
||||
float freeAngle = Mathf.PI / 8f;
|
||||
if (placement.TryPlaceAt(entry, new Vector3(Mathf.Cos(freeAngle) * 3.5f, Mathf.Sin(freeAngle) * 3.5f, 0), out string limitReason) || limitReason != "Turmlimit erreicht")
|
||||
throw new Exception("Tower limit failed.");
|
||||
double delayDeadline = EditorApplication.timeSinceStartup + 1.5;
|
||||
EditorApplication.CallbackFunction delayCheck = null;
|
||||
delayCheck = () => {
|
||||
if (EditorApplication.timeSinceStartup < delayDeadline) return;
|
||||
EditorApplication.update -= delayCheck;
|
||||
try {
|
||||
if (placement.IsWaitingForReturn) throw new Exception("Book delay never expired.");
|
||||
var group = menu.GetComponentInParent<CanvasGroup>();
|
||||
if (!group.blocksRaycasts) throw new Exception("Book input not restored after delay.");
|
||||
if (placement.Begin(entry, validScreen)) throw new Exception("Limit should prevent drag.");
|
||||
var toast = controller.transform.Find("FeedbackBox") ?? controller.transform.Find("Feedbackbox");
|
||||
var message = controller.transform.Find("FeedbackMessage").GetComponent<TMPro.TMP_Text>();
|
||||
if (!toast || !toast.gameObject.activeSelf || message.text != "Turmlimit erreicht")
|
||||
throw new Exception("Limit notice did not show background and message.");
|
||||
double toastDeadline = EditorApplication.timeSinceStartup + 2.9;
|
||||
EditorApplication.CallbackFunction toastCheck = null;
|
||||
toastCheck = () => {
|
||||
if (EditorApplication.timeSinceStartup < toastDeadline) return;
|
||||
EditorApplication.update -= toastCheck;
|
||||
try {
|
||||
if (toast.gameObject.activeSelf || message.text != "") throw new Exception("Notice did not disappear.");
|
||||
controller.Close();
|
||||
Debug.Log("HANDBOOK_RUNTIME_VALIDATION_OK: Category reset, 0.5-second placement delay, limit notice background and automatic dismissal passed; existing placement checks passed.");
|
||||
EditorApplication.Exit(0);
|
||||
} catch (Exception e) { Debug.LogException(e); EditorApplication.Exit(1); }
|
||||
};
|
||||
EditorApplication.update += toastCheck;
|
||||
} catch (Exception e) { Debug.LogException(e); EditorApplication.Exit(1); }
|
||||
};
|
||||
EditorApplication.update += delayCheck;
|
||||
} catch (Exception e) { Debug.LogException(e); EditorApplication.Exit(1); }
|
||||
};
|
||||
EditorApplication.update += check;
|
||||
}
|
||||
catch (Exception e) { Debug.LogException(e); EditorApplication.Exit(1); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 79121ad9902be844f8f2b736dbf9adb5
|
||||
@@ -0,0 +1,199 @@
|
||||
using TMPro;
|
||||
using UnityEngine;
|
||||
using UnityEngine.EventSystems;
|
||||
using UnityEngine.InputSystem;
|
||||
using UnityEngine.UI;
|
||||
|
||||
namespace DepthsOfGreed.HandbookUI
|
||||
{
|
||||
public sealed class HandbookController : MonoBehaviour
|
||||
{
|
||||
[SerializeField] private GameObject closedBook;
|
||||
[SerializeField] private GameObject openBook;
|
||||
[SerializeField] private Button bookButton;
|
||||
[SerializeField] private Button closeButton;
|
||||
[SerializeField] private RectTransform closedTabsRoot;
|
||||
[SerializeField] private RectTransform openTabsRoot;
|
||||
[SerializeField] private Button[] closedTabs;
|
||||
[SerializeField] private Button[] openTabs;
|
||||
[SerializeField] private GameObject[] pages;
|
||||
[SerializeField] private GameObject testTowerPrefab;
|
||||
[SerializeField] private HandbookTowerCatalog towerCatalog;
|
||||
[Tooltip("Wartezeit nach erfolgreichem Platzieren, bevor das Buch hochfährt.")]
|
||||
[SerializeField, Min(0)] private float successfulPlacementDelay = 0.5f;
|
||||
[SerializeField] private float hoverDistance = 115f;
|
||||
[SerializeField] private float animationSpeed = 14f;
|
||||
|
||||
private readonly string[] titles = { "Bauen", "Statistik", "Upgrades", "Index" };
|
||||
private Vector2[] closedPositions, openPositions;
|
||||
private TMP_Text[] closedLabels, openLabels;
|
||||
private RectTransform activeLayer;
|
||||
private int selected, hoveredClosed = -1, hoveredOpen = -1;
|
||||
private bool isOpen, bookHovered;
|
||||
private Vector3 bookScale;
|
||||
private BuildMenuController buildMenu;
|
||||
private TestPlacementController placement;
|
||||
private HandbookIndexController indexMenu;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
if (!closedBook || !openBook || !bookButton || !closeButton ||
|
||||
!openTabsRoot || !closedTabsRoot || closedTabs.Length != 4 ||
|
||||
openTabs.Length != 4 || pages.Length != 4)
|
||||
{
|
||||
Debug.LogError("Handbuch: Inspector-Verbindungen fehlen.", this);
|
||||
enabled = false;
|
||||
return;
|
||||
}
|
||||
closedPositions = PrepareTabs(closedTabs, out closedLabels, false);
|
||||
openPositions = PrepareTabs(openTabs, out openLabels, true);
|
||||
bookScale = bookButton.transform.localScale;
|
||||
var layer = new GameObject("ActiveTabLayer", typeof(RectTransform));
|
||||
activeLayer = layer.GetComponent<RectTransform>();
|
||||
activeLayer.SetParent(openTabsRoot.parent, false);
|
||||
activeLayer.anchorMin = openTabsRoot.anchorMin;
|
||||
activeLayer.anchorMax = openTabsRoot.anchorMax;
|
||||
activeLayer.pivot = openTabsRoot.pivot;
|
||||
activeLayer.offsetMin = openTabsRoot.offsetMin;
|
||||
activeLayer.offsetMax = openTabsRoot.offsetMax;
|
||||
var background = openBook.transform.Find("Background");
|
||||
if (background) activeLayer.SetSiblingIndex(background.GetSiblingIndex() + 1);
|
||||
bookButton.onClick.AddListener(() => Open(0));
|
||||
closeButton.onClick.AddListener(Close);
|
||||
AddHover(bookButton.gameObject, () => bookHovered = true, () => bookHovered = false);
|
||||
buildMenu = pages[0].AddComponent<BuildMenuController>();
|
||||
buildMenu.Initialize(towerCatalog);
|
||||
placement = gameObject.AddComponent<TestPlacementController>();
|
||||
placement.Initialize(this, buildMenu, (RectTransform)openBook.transform, testTowerPrefab);
|
||||
placement.SuccessfulPlacementDelay = successfulPlacementDelay;
|
||||
buildMenu.Placement = placement;
|
||||
indexMenu = pages[3].AddComponent<HandbookIndexController>();
|
||||
indexMenu.Initialize(towerCatalog);
|
||||
Close();
|
||||
}
|
||||
|
||||
private Vector2[] PrepareTabs(Button[] tabs, out TMP_Text[] labels, bool opened)
|
||||
{
|
||||
var positions = new Vector2[tabs.Length];
|
||||
labels = new TMP_Text[tabs.Length];
|
||||
for (int i = 0; i < tabs.Length; i++)
|
||||
{
|
||||
int index = i;
|
||||
if (!opened)
|
||||
{
|
||||
var marker = (RectTransform)tabs[i].transform;
|
||||
marker.sizeDelta = new Vector2(marker.sizeDelta.x + 25f, marker.sizeDelta.y);
|
||||
marker.anchoredPosition += Vector2.right * 25f;
|
||||
}
|
||||
positions[i] = ((RectTransform)tabs[i].transform).anchoredPosition;
|
||||
labels[i] = tabs[i].GetComponentInChildren<TMP_Text>(true);
|
||||
if (labels[i])
|
||||
{
|
||||
var text = labels[i];
|
||||
text.text = titles[i];
|
||||
text.raycastTarget = false;
|
||||
text.fontSize = opened ? 20 : 18;
|
||||
text.enableAutoSizing = true;
|
||||
text.fontSizeMin = 14;
|
||||
text.fontSizeMax = opened ? 20 : 18;
|
||||
text.alignment = TextAlignmentOptions.MidlineLeft;
|
||||
var rect = text.rectTransform;
|
||||
rect.anchorMin = Vector2.zero;
|
||||
rect.anchorMax = Vector2.one;
|
||||
rect.offsetMin = new Vector2(opened ? 65 : 48, 4);
|
||||
rect.offsetMax = new Vector2(-6, -4);
|
||||
text.gameObject.SetActive(false);
|
||||
}
|
||||
tabs[i].onClick.AddListener(() => Open(index));
|
||||
AddHover(tabs[i].gameObject,
|
||||
() => { if (opened) hoveredOpen = index; else hoveredClosed = index; },
|
||||
() => { if (opened) { if (hoveredOpen == index) hoveredOpen = -1; }
|
||||
else if (hoveredClosed == index) hoveredClosed = -1; });
|
||||
}
|
||||
return positions;
|
||||
}
|
||||
|
||||
private static void AddHover(GameObject target, UnityEngine.Events.UnityAction enter,
|
||||
UnityEngine.Events.UnityAction exit)
|
||||
{
|
||||
var trigger = target.GetComponent<EventTrigger>();
|
||||
if (!trigger) trigger = target.AddComponent<EventTrigger>();
|
||||
var entry = new EventTrigger.Entry { eventID = EventTriggerType.PointerEnter };
|
||||
entry.callback.AddListener(_ => enter());
|
||||
trigger.triggers.Add(entry);
|
||||
var leave = new EventTrigger.Entry { eventID = EventTriggerType.PointerExit };
|
||||
leave.callback.AddListener(_ => exit());
|
||||
trigger.triggers.Add(leave);
|
||||
}
|
||||
|
||||
public void Open(int index)
|
||||
{
|
||||
if (index < 0 || index >= pages.Length) return;
|
||||
bool samePage = isOpen && selected == index;
|
||||
selected = index;
|
||||
isOpen = true;
|
||||
hoveredClosed = -1;
|
||||
bookHovered = false;
|
||||
closedBook.SetActive(false);
|
||||
openBook.SetActive(true);
|
||||
for (int i = 0; i < pages.Length; i++)
|
||||
{
|
||||
pages[i].SetActive(i == index);
|
||||
var rect = (RectTransform)openTabs[i].transform;
|
||||
rect.SetParent(i == selected ? activeLayer : openTabsRoot, false);
|
||||
}
|
||||
if (index == 3 && !samePage && indexMenu) indexMenu.ResetForEntry();
|
||||
if (samePage)
|
||||
foreach (var scroll in pages[index].GetComponentsInChildren<ScrollRect>(true))
|
||||
scroll.verticalNormalizedPosition = 1f;
|
||||
}
|
||||
|
||||
public void Close()
|
||||
{
|
||||
if (placement && placement.IsDragging) placement.Cancel();
|
||||
if (placement) placement.ResetBookPresentation();
|
||||
if (buildMenu) buildMenu.ResetForClose();
|
||||
if (indexMenu) indexMenu.ClearSelection();
|
||||
isOpen = false;
|
||||
hoveredOpen = hoveredClosed = -1;
|
||||
bookHovered = false;
|
||||
for (int i = 0; i < openTabs.Length; i++)
|
||||
{
|
||||
((RectTransform)openTabs[i].transform).anchoredPosition = openPositions[i];
|
||||
if (openLabels[i]) openLabels[i].gameObject.SetActive(false);
|
||||
}
|
||||
openBook.SetActive(false);
|
||||
closedBook.SetActive(true);
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
if (isOpen && (!placement || !placement.ConsumedCancelThisFrame) &&
|
||||
(!placement || !placement.IsDragging) && Keyboard.current != null && Keyboard.current.escapeKey.wasPressedThisFrame)
|
||||
Close();
|
||||
float blend = 1f - Mathf.Exp(-animationSpeed * Time.unscaledDeltaTime);
|
||||
if (!isOpen)
|
||||
{
|
||||
bookButton.transform.localScale = Vector3.Lerp(bookButton.transform.localScale,
|
||||
bookScale * (bookHovered ? 1.04f : 1f), blend);
|
||||
AnimateTabs(closedTabs, closedPositions, closedLabels, hoveredClosed, -1, blend);
|
||||
}
|
||||
else AnimateTabs(openTabs, openPositions, openLabels, hoveredOpen, selected, blend);
|
||||
}
|
||||
|
||||
private void AnimateTabs(Button[] tabs, Vector2[] positions, TMP_Text[] labels,
|
||||
int hovered, int active, float blend)
|
||||
{
|
||||
for (int i = 0; i < tabs.Length; i++)
|
||||
{
|
||||
bool show = i == hovered || i == active;
|
||||
var rect = (RectTransform)tabs[i].transform;
|
||||
// Reveal the full marker while retaining a small overlap with the page.
|
||||
float distance = Mathf.Clamp(hoverDistance, 0f, Mathf.Max(0f, positions[i].x - 10f));
|
||||
var target = positions[i] + (show ? Vector2.left * distance : Vector2.zero);
|
||||
rect.anchoredPosition = Vector2.Lerp(rect.anchoredPosition, target, blend);
|
||||
if (labels[i]) labels[i].gameObject.SetActive(show);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 31f25b4362124801930b25ce73fa3d62
|
||||
@@ -0,0 +1,150 @@
|
||||
using System.Collections.Generic;
|
||||
using TMPro;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
|
||||
namespace DepthsOfGreed.HandbookUI
|
||||
{
|
||||
public sealed class HandbookIndexController : MonoBehaviour
|
||||
{
|
||||
public HandbookTowerEntry SelectedEntry { get; private set; }
|
||||
public int VisibleEntryCount => currentFilter == 2 ? 0 : entries.Count;
|
||||
public ScrollRect ListScroll => scroll;
|
||||
private ScrollRect scroll;
|
||||
private Button[] filters;
|
||||
private readonly List<HandbookTowerEntry> entries = new List<HandbookTowerEntry>();
|
||||
private readonly List<Button> rows = new List<Button>();
|
||||
private TMP_Text detailName, description, emptyMessage;
|
||||
private Image detailIcon;
|
||||
private Sprite placeholder;
|
||||
private Color placeholderColor;
|
||||
private int currentFilter;
|
||||
|
||||
public void Initialize(HandbookTowerCatalog catalog)
|
||||
{
|
||||
scroll = transform.Find("IndexLeft/EntryScrollView").GetComponent<ScrollRect>();
|
||||
filters = new[] {
|
||||
transform.Find("IndexLeft/FilterBar/Filter_All").GetComponent<Button>(),
|
||||
transform.Find("IndexLeft/FilterBar/Filter_Towers").GetComponent<Button>(),
|
||||
transform.Find("IndexLeft/FilterBar/Filter_Enemies").GetComponent<Button>()
|
||||
};
|
||||
detailName = transform.Find("IndexRight/DetailNameText").GetComponent<TMP_Text>();
|
||||
description = transform.Find("IndexRight/DetailDescriptionText").GetComponent<TMP_Text>();
|
||||
detailIcon = transform.Find("IndexRight/DetailIcon").GetComponent<Image>();
|
||||
placeholder = detailIcon.sprite;
|
||||
placeholderColor = detailIcon.color;
|
||||
var template = scroll.content.GetChild(0).GetComponent<Button>();
|
||||
if (catalog && catalog.towers != null)
|
||||
foreach (var entry in catalog.towers)
|
||||
{
|
||||
if (!entry) continue;
|
||||
int index = entries.Count;
|
||||
entries.Add(entry);
|
||||
var row = Instantiate(template, scroll.content);
|
||||
row.name = "IndexEntry_" + entry.id;
|
||||
row.gameObject.SetActive(true);
|
||||
row.image.color = Color.white;
|
||||
var label = row.transform.Find("NameText").GetComponent<TMP_Text>();
|
||||
label.text = entry.displayName;
|
||||
label.color = Color.black;
|
||||
label.raycastTarget = false;
|
||||
label.enableAutoSizing = true;
|
||||
label.fontSizeMin = 16;
|
||||
label.fontSizeMax = 24;
|
||||
var icon = row.transform.Find("Icon").GetComponent<Image>();
|
||||
if (entry.icon) { icon.sprite = entry.icon; icon.color = Color.white; }
|
||||
icon.preserveAspect = true;
|
||||
icon.raycastTarget = false;
|
||||
row.onClick.RemoveAllListeners();
|
||||
row.onClick.AddListener(() => SelectEntry(index));
|
||||
rows.Add(row);
|
||||
}
|
||||
template.gameObject.SetActive(false);
|
||||
var empty = new GameObject("EmptyListMessage", typeof(RectTransform), typeof(TextMeshProUGUI), typeof(LayoutElement));
|
||||
empty.transform.SetParent(scroll.content, false);
|
||||
emptyMessage = empty.GetComponent<TMP_Text>();
|
||||
emptyMessage.font = description.font;
|
||||
emptyMessage.fontSize = 22;
|
||||
emptyMessage.color = new Color(0.3f, 0.3f, 0.3f);
|
||||
emptyMessage.alignment = TextAlignmentOptions.MidlineLeft;
|
||||
emptyMessage.raycastTarget = false;
|
||||
empty.GetComponent<LayoutElement>().preferredHeight = 70;
|
||||
for (int i = 0; i < filters.Length; i++)
|
||||
{
|
||||
int index = i;
|
||||
filters[i].onClick.AddListener(() => SelectFilter(index));
|
||||
}
|
||||
ResetForEntry();
|
||||
}
|
||||
|
||||
public void ResetForEntry()
|
||||
{
|
||||
SelectFilter(0, true);
|
||||
}
|
||||
|
||||
public void SelectFilter(int index, bool force = false)
|
||||
{
|
||||
if (index < 0 || index > 2 || (!force && currentFilter == index)) return;
|
||||
currentFilter = index;
|
||||
foreach (var row in rows) row.gameObject.SetActive(index != 2);
|
||||
bool empty = index == 2 || rows.Count == 0;
|
||||
emptyMessage.gameObject.SetActive(empty);
|
||||
emptyMessage.text = index == 2 ? "Noch keine Gegner-Einträge" : "Noch keine Einträge";
|
||||
for (int i = 0; i < filters.Length; i++)
|
||||
{
|
||||
filters[i].image.color = Color.white;
|
||||
var colors = filters[i].colors;
|
||||
colors.normalColor = i == index ? new Color(1, 0.72f, 0.2f) : new Color(0.82f, 0.82f, 0.82f);
|
||||
colors.highlightedColor = i == index ? new Color(1, 0.82f, 0.4f) : Color.white;
|
||||
colors.selectedColor = colors.normalColor;
|
||||
filters[i].colors = colors;
|
||||
}
|
||||
ClearSelection();
|
||||
ResetScroll();
|
||||
}
|
||||
|
||||
public void SelectEntry(int index)
|
||||
{
|
||||
if (currentFilter == 2 || index < 0 || index >= entries.Count) return;
|
||||
SelectedEntry = entries[index];
|
||||
detailName.text = SelectedEntry.displayName;
|
||||
description.text = SelectedEntry.description;
|
||||
detailIcon.gameObject.SetActive(true);
|
||||
detailIcon.sprite = SelectedEntry.icon ? SelectedEntry.icon : placeholder;
|
||||
detailIcon.color = SelectedEntry.icon ? Color.white : placeholderColor;
|
||||
detailIcon.preserveAspect = true;
|
||||
RefreshSelectionColors();
|
||||
}
|
||||
|
||||
public void ClearSelection()
|
||||
{
|
||||
SelectedEntry = null;
|
||||
detailIcon.gameObject.SetActive(false);
|
||||
detailName.text = "";
|
||||
description.text = "Wähle links einen Eintrag aus.";
|
||||
RefreshSelectionColors();
|
||||
}
|
||||
|
||||
private void RefreshSelectionColors()
|
||||
{
|
||||
for (int i = 0; i < rows.Count; i++)
|
||||
{
|
||||
bool selected = entries[i] == SelectedEntry;
|
||||
var colors = rows[i].colors;
|
||||
colors.normalColor = selected ? new Color(0.58f, 0.58f, 0.58f) : new Color(0.86f, 0.86f, 0.86f);
|
||||
colors.highlightedColor = selected ? new Color(0.64f, 0.64f, 0.64f) : new Color(0.94f, 0.94f, 0.94f);
|
||||
colors.selectedColor = colors.normalColor;
|
||||
rows[i].colors = colors;
|
||||
}
|
||||
}
|
||||
|
||||
public void ResetScroll()
|
||||
{
|
||||
scroll.StopMovement();
|
||||
Canvas.ForceUpdateCanvases();
|
||||
LayoutRebuilder.ForceRebuildLayoutImmediate(scroll.content);
|
||||
scroll.verticalNormalizedPosition = 1f;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 696bee932f5c28644b0b91519fa1e914
|
||||
@@ -0,0 +1,11 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace DepthsOfGreed.HandbookUI
|
||||
{
|
||||
[CreateAssetMenu(menuName = "Depths of Greed/Handbuch/Turmkatalog", fileName = "Turmkatalog")]
|
||||
public sealed class HandbookTowerCatalog : ScriptableObject
|
||||
{
|
||||
[Tooltip("Die Reihenfolge innerhalb einer Kategorie bestimmt die Reihenfolge im Buch.")]
|
||||
public HandbookTowerEntry[] towers;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3012a600391588c41b9af390fcd07c48
|
||||
@@ -0,0 +1,30 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace DepthsOfGreed.HandbookUI
|
||||
{
|
||||
public enum HandbookTowerCategory { Munition, Energie, Spezial }
|
||||
|
||||
[CreateAssetMenu(menuName = "Depths of Greed/Handbuch/Turmtyp", fileName = "NeuerTurmtyp")]
|
||||
public sealed class HandbookTowerEntry : ScriptableObject
|
||||
{
|
||||
[Tooltip("Stabile ID für die spätere Gameplay-Anbindung. Nach Zuordnung nicht ändern.")]
|
||||
public string id;
|
||||
public string displayName;
|
||||
public HandbookTowerCategory category;
|
||||
public Sprite icon;
|
||||
[Min(0)] public int energyCost;
|
||||
public string summary;
|
||||
[TextArea(3, 8)] public string description;
|
||||
[Tooltip("Kreis, der die gesamte Basis umschließt. Muss vollständig auf den Ring passen.")]
|
||||
[Min(0.001f)] public float baseRadius = 0.36f;
|
||||
[Tooltip("Abstandskreis: darf andere Abstandskreise nicht überlappen.")]
|
||||
[Min(0.001f)] public float placementRadius = 0.6f;
|
||||
|
||||
private void OnValidate()
|
||||
{
|
||||
baseRadius = Mathf.Max(0.001f, baseRadius);
|
||||
placementRadius = Mathf.Max(baseRadius, placementRadius);
|
||||
energyCost = Mathf.Max(0, energyCost);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 84e7b6df881a39543ae3e00951e9b29b
|
||||
@@ -0,0 +1,330 @@
|
||||
using System.Collections.Generic;
|
||||
using TMPro;
|
||||
using UnityEngine;
|
||||
using UnityEngine.InputSystem;
|
||||
using UnityEngine.UI;
|
||||
|
||||
namespace DepthsOfGreed.HandbookUI
|
||||
{
|
||||
// Prototype backend only: no dependency on enemy, tower or ammunition scripts.
|
||||
public sealed class TestPlacementController : MonoBehaviour
|
||||
{
|
||||
public bool IsDragging { get; private set; }
|
||||
public bool ConsumedCancelThisFrame => cancelFrame == Time.frameCount;
|
||||
public int TowerCount => placed.Count;
|
||||
public int Energy { get; private set; } = 2000;
|
||||
public int MaximumTowers = 8;
|
||||
public float SuccessfulPlacementDelay = 0.5f;
|
||||
public bool IsWaitingForReturn => Time.unscaledTime < returnAfter;
|
||||
private float returnAfter;
|
||||
private int cancelFrame = -1;
|
||||
private RectTransform book;
|
||||
private Vector2 bookHome;
|
||||
private CanvasGroup bookGroup;
|
||||
private GameObject prefab, preview, controls;
|
||||
private Transform container, area;
|
||||
private SpriteRenderer ghost, footprint;
|
||||
private TMP_Text controlsText, feedback, resources, buildHint;
|
||||
private Image feedbackBox;
|
||||
private RectTransform feedbackBoxRect;
|
||||
private float messageStarted;
|
||||
private Color feedbackBackground;
|
||||
private Camera worldCamera;
|
||||
private float innerRadius, outerRadius, messageUntil;
|
||||
private HandbookTowerEntry draggingEntry;
|
||||
private Vector3 target;
|
||||
private readonly List<PlacedRecord> placed = new List<PlacedRecord>();
|
||||
private readonly List<LineRenderer> guides = new List<LineRenderer>();
|
||||
private LineRenderer previewOutline, innerOutline, outerOutline;
|
||||
private Material lineMaterial;
|
||||
private struct PlacedRecord { public Vector3 position; public float radius; public GameObject instance; }
|
||||
|
||||
public void Initialize(HandbookController owner, BuildMenuController menu, RectTransform openBook, GameObject testPrefab)
|
||||
{
|
||||
book = openBook;
|
||||
bookHome = book.anchoredPosition;
|
||||
bookGroup = book.GetComponent<CanvasGroup>();
|
||||
prefab = testPrefab;
|
||||
worldCamera = Camera.main;
|
||||
var test = GameObject.Find("PlacementTest");
|
||||
if (!test || !prefab || !worldCamera)
|
||||
{
|
||||
Debug.LogError("Testplatzierung: TestTower-Prefab, PlacementTest oder Main Camera fehlt.", this);
|
||||
enabled = false;
|
||||
return;
|
||||
}
|
||||
area = test.transform.Find("BuildArea");
|
||||
container = test.transform.Find("PlacedTowers") ?? test.transform.Find("PlaceTowers");
|
||||
preview = test.transform.Find("PlacementPreview").gameObject;
|
||||
ghost = preview.transform.Find("GhostVisual").GetComponent<SpriteRenderer>();
|
||||
footprint = preview.transform.Find("FootprintVisual").GetComponent<SpriteRenderer>();
|
||||
var controlTransform = transform.Find("PlacementControlBar") ?? transform.Find("PlacementController");
|
||||
if (!area || !container || !controlTransform)
|
||||
{
|
||||
Debug.LogError("Testplatzierung: Baubereich, Turmcontainer oder Kontrollleiste fehlt.", this);
|
||||
enabled = false;
|
||||
return;
|
||||
}
|
||||
controls = controlTransform.gameObject;
|
||||
controlsText = controls.GetComponentInChildren<TMP_Text>(true);
|
||||
feedback = transform.Find("FeedbackMessage").GetComponent<TMP_Text>();
|
||||
var boxTransform = transform.Find("FeedbackBox") ?? transform.Find("Feedbackbox");
|
||||
if (boxTransform)
|
||||
{
|
||||
feedbackBox = boxTransform.GetComponent<Image>();
|
||||
feedbackBoxRect = (RectTransform)boxTransform;
|
||||
feedbackBackground = feedbackBox.color;
|
||||
feedbackBox.raycastTarget = false;
|
||||
feedbackBox.gameObject.SetActive(false);
|
||||
}
|
||||
resources = menu.transform.Find("RightPage/ResourcesText").GetComponent<TMP_Text>();
|
||||
buildHint = menu.transform.Find("BuildHintText").GetComponent<TMP_Text>();
|
||||
innerRadius = RadiusOf("BackgroundTower", 3f);
|
||||
outerRadius = RadiusOf("BackgroundOuterwall", 4f);
|
||||
lineMaterial = new Material(Shader.Find("Sprites/Default"));
|
||||
previewOutline = MakeCircle("PlacementOutline", preview.transform, 11);
|
||||
innerOutline = MakeCircle("BuildArea_Inner", area, 8);
|
||||
outerOutline = MakeCircle("BuildArea_Outer", area, 8);
|
||||
DrawCircle(innerOutline, innerRadius);
|
||||
DrawCircle(outerOutline, outerRadius);
|
||||
ShowGuides(false);
|
||||
preview.SetActive(false);
|
||||
controls.SetActive(false);
|
||||
RefreshResources();
|
||||
}
|
||||
|
||||
private static float RadiusOf(string name, float fallback)
|
||||
{
|
||||
var obj = GameObject.Find(name);
|
||||
var renderer = obj ? obj.GetComponent<SpriteRenderer>() : null;
|
||||
return renderer ? Mathf.Min(renderer.bounds.extents.x, renderer.bounds.extents.y) : fallback;
|
||||
}
|
||||
|
||||
public bool Begin(HandbookTowerEntry entry, Vector2 screenPosition)
|
||||
{
|
||||
if (!enabled || IsDragging || IsWaitingForReturn || entry == null) return false;
|
||||
if (placed.Count >= MaximumTowers) { Message("Turmlimit erreicht"); return false; }
|
||||
if (Energy < entry.energyCost) { Message("Nicht genug Energie"); return false; }
|
||||
draggingEntry = entry;
|
||||
IsDragging = true;
|
||||
preview.SetActive(true);
|
||||
footprint.transform.localScale = new Vector3(entry.placementRadius * 2f, entry.placementRadius * 2f, 1f);
|
||||
DrawCircle(previewOutline, entry.placementRadius);
|
||||
controls.SetActive(true);
|
||||
bookGroup.blocksRaycasts = false;
|
||||
ShowGuides(true);
|
||||
foreach (var record in placed)
|
||||
{
|
||||
var guide = MakeCircle("ExistingTowerRadius", container, 8);
|
||||
guide.transform.position = record.position;
|
||||
DrawCircle(guide, record.radius);
|
||||
Tint(guide, new Color(1f, 1f, 1f, 0.5f));
|
||||
guides.Add(guide);
|
||||
}
|
||||
Move(screenPosition);
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Move(Vector2 screenPosition)
|
||||
{
|
||||
if (!IsDragging) return;
|
||||
var ray = worldCamera.ScreenPointToRay(screenPosition);
|
||||
var plane = new Plane(Vector3.forward, new Vector3(0, 0, 0));
|
||||
if (!plane.Raycast(ray, out float distance)) return;
|
||||
target = ray.GetPoint(distance);
|
||||
target.z = 0;
|
||||
preview.transform.position = target;
|
||||
string reason = Check(draggingEntry, target);
|
||||
bool outside = reason == "Außerhalb des Schienenbereichs";
|
||||
Color color = outside ? Color.gray : reason == null ? Color.green : Color.red;
|
||||
footprint.color = new Color(color.r, color.g, color.b, outside ? 0.08f : 0.18f);
|
||||
ghost.color = new Color(1f, 1f, 1f, outside ? 0.3f : 0.65f);
|
||||
Tint(previewOutline, color);
|
||||
DrawCircle(previewOutline, draggingEntry.placementRadius, outside);
|
||||
controlsText.text = "Loslassen: Platzieren · Rechtsklick / Esc: Abbrechen";
|
||||
if (reason != null && !outside) controlsText.text += "\n" + reason;
|
||||
}
|
||||
|
||||
public void End(Vector2 screenPosition)
|
||||
{
|
||||
if (!IsDragging) return;
|
||||
Move(screenPosition);
|
||||
bool success = TryPlaceAt(draggingEntry, target, out string reason);
|
||||
if (!success) Message(reason);
|
||||
Finish();
|
||||
if (success)
|
||||
{
|
||||
returnAfter = Time.unscaledTime + Mathf.Max(0, SuccessfulPlacementDelay);
|
||||
bookGroup.blocksRaycasts = false;
|
||||
}
|
||||
}
|
||||
|
||||
public string Check(HandbookTowerEntry entry, Vector3 position)
|
||||
{
|
||||
if (entry == null) return "Kein Turm ausgewählt";
|
||||
float distance = Vector2.Distance(position, area.position);
|
||||
if (distance - entry.baseRadius < innerRadius || distance + entry.baseRadius > outerRadius)
|
||||
return "Außerhalb des Schienenbereichs";
|
||||
foreach (var record in placed)
|
||||
if (Vector2.Distance(position, record.position) < entry.placementRadius + record.radius)
|
||||
return "Zu nah an einem anderen Turm";
|
||||
if (placed.Count >= MaximumTowers) return "Turmlimit erreicht";
|
||||
if (Energy < entry.energyCost) return "Nicht genug Energie";
|
||||
return null;
|
||||
}
|
||||
|
||||
public bool TryPlaceAt(HandbookTowerEntry entry, Vector3 position, out string reason)
|
||||
{
|
||||
reason = Check(entry, position);
|
||||
if (reason != null) return false;
|
||||
var tower = Instantiate(prefab, position, Quaternion.identity, container);
|
||||
tower.name = entry.displayName + " (Test)";
|
||||
placed.Add(new PlacedRecord { position = position, radius = entry.placementRadius, instance = tower });
|
||||
Energy -= entry.energyCost;
|
||||
RefreshResources();
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Cancel()
|
||||
{
|
||||
if (!IsDragging) return;
|
||||
cancelFrame = Time.frameCount;
|
||||
Finish();
|
||||
}
|
||||
|
||||
private void Finish()
|
||||
{
|
||||
IsDragging = false;
|
||||
draggingEntry = null;
|
||||
preview.SetActive(false);
|
||||
controls.SetActive(false);
|
||||
bookGroup.blocksRaycasts = true;
|
||||
ShowGuides(false);
|
||||
foreach (var guide in guides) Destroy(guide.gameObject);
|
||||
guides.Clear();
|
||||
}
|
||||
|
||||
public void ResetBookPresentation()
|
||||
{
|
||||
returnAfter = 0;
|
||||
if (book) book.anchoredPosition = bookHome;
|
||||
if (bookGroup) bookGroup.blocksRaycasts = true;
|
||||
ClearFeedback();
|
||||
}
|
||||
|
||||
private void LateUpdate()
|
||||
{
|
||||
if (!enabled || !book) return;
|
||||
if (IsDragging && Mouse.current != null)
|
||||
{
|
||||
if (Mouse.current.rightButton.wasPressedThisFrame ||
|
||||
(Keyboard.current != null && Keyboard.current.escapeKey.wasPressedThisFrame)) Cancel();
|
||||
else Move(Mouse.current.position.ReadValue());
|
||||
}
|
||||
bool lowered = IsDragging || IsWaitingForReturn;
|
||||
if (!lowered) bookGroup.blocksRaycasts = true;
|
||||
var position = lowered ? new Vector2(bookHome.x, -book.rect.height + 100f) : bookHome;
|
||||
book.anchoredPosition = Vector2.Lerp(book.anchoredPosition, position,
|
||||
1f - Mathf.Exp(-18f * Time.unscaledDeltaTime));
|
||||
if (IsDragging)
|
||||
{
|
||||
bool outside = Check(draggingEntry, target) == "Außerhalb des Schienenbereichs";
|
||||
float alpha = outside ? 0.35f + 0.2f * Mathf.Sin(Time.unscaledTime * 5f) : 0.4f;
|
||||
Tint(innerOutline, new Color(1f, 0.8f, 0.3f, alpha));
|
||||
Tint(outerOutline, new Color(1f, 0.8f, 0.3f, alpha));
|
||||
}
|
||||
UpdateFeedback();
|
||||
}
|
||||
|
||||
private void Message(string reason)
|
||||
{
|
||||
feedback.gameObject.SetActive(true);
|
||||
feedback.transform.SetAsLastSibling();
|
||||
feedback.color = Color.white;
|
||||
feedback.text = reason;
|
||||
messageStarted = Time.unscaledTime;
|
||||
messageUntil = messageStarted + 2.65f;
|
||||
if (feedbackBox)
|
||||
{
|
||||
feedbackBox.gameObject.SetActive(true);
|
||||
feedbackBox.transform.SetAsLastSibling();
|
||||
feedback.transform.SetAsLastSibling();
|
||||
}
|
||||
UpdateFeedback();
|
||||
}
|
||||
|
||||
private void UpdateFeedback()
|
||||
{
|
||||
if (!feedback || messageUntil <= 0) return;
|
||||
float elapsed = Time.unscaledTime - messageStarted;
|
||||
if (Time.unscaledTime >= messageUntil) { ClearFeedback(); return; }
|
||||
float alpha = elapsed > 2.4f ? Mathf.Clamp01((messageUntil - Time.unscaledTime) / 0.25f) : 1f;
|
||||
feedback.color = new Color(1, 1, 1, alpha);
|
||||
if (feedbackBox)
|
||||
{
|
||||
float pulse = elapsed < 0.4f ? Mathf.Pow(Mathf.Sin(elapsed / 0.4f * Mathf.PI * 2f), 2f) : 0;
|
||||
Color color = Color.Lerp(feedbackBackground, new Color(0.48f, 0.34f, 0.15f, 1), pulse);
|
||||
color.a = alpha;
|
||||
feedbackBox.color = color;
|
||||
float canvasHeight = ((RectTransform)transform).rect.height;
|
||||
float y = Mathf.Min(-10f, book.anchoredPosition.y + book.rect.height - canvasHeight + 70f);
|
||||
feedbackBoxRect.anchoredPosition = new Vector2(0, y);
|
||||
feedback.rectTransform.anchoredPosition = new Vector2(0, y);
|
||||
}
|
||||
}
|
||||
|
||||
private void ClearFeedback()
|
||||
{
|
||||
messageUntil = 0;
|
||||
if (feedback) { feedback.text = ""; feedback.color = Color.white; }
|
||||
if (feedbackBox) feedbackBox.gameObject.SetActive(false);
|
||||
}
|
||||
private void RefreshResources()
|
||||
{
|
||||
resources.text = "Energie: " + Energy + " · Gedärme: 100 (Test)\nTürme: " + placed.Count + "/" + MaximumTowers;
|
||||
if (buildHint)
|
||||
{
|
||||
bool full = placed.Count >= MaximumTowers;
|
||||
buildHint.text = full ? "Turmlimit erreicht (" + placed.Count + "/" + MaximumTowers + ") · Klicken: Infos" : "Ziehen: Bauen · Klicken: Infos";
|
||||
buildHint.color = full ? new Color(0.7f, 0.15f, 0.1f) : new Color(0.3f, 0.3f, 0.3f);
|
||||
}
|
||||
}
|
||||
private void ShowGuides(bool show)
|
||||
{
|
||||
innerOutline.gameObject.SetActive(show);
|
||||
outerOutline.gameObject.SetActive(show);
|
||||
}
|
||||
private LineRenderer MakeCircle(string name, Transform parent, int order)
|
||||
{
|
||||
var obj = new GameObject(name);
|
||||
obj.transform.SetParent(parent, false);
|
||||
var line = obj.AddComponent<LineRenderer>();
|
||||
line.sharedMaterial = lineMaterial;
|
||||
line.useWorldSpace = false;
|
||||
line.widthMultiplier = 0.025f;
|
||||
line.sortingOrder = order;
|
||||
return line;
|
||||
}
|
||||
private static void Tint(LineRenderer line, Color color) { line.startColor = line.endColor = color; }
|
||||
private static void DrawCircle(LineRenderer line, float radius, bool dashed = false)
|
||||
{
|
||||
const int segments = 96;
|
||||
line.loop = true;
|
||||
line.positionCount = segments;
|
||||
for (int i = 0; i < segments; i++)
|
||||
{
|
||||
float angle = i * Mathf.PI * 2f / segments;
|
||||
line.SetPosition(i, new Vector3(Mathf.Cos(angle) * radius, Mathf.Sin(angle) * radius, 0));
|
||||
}
|
||||
// Alternating width provides a procedural broken outline without an extra sprite.
|
||||
if (dashed)
|
||||
{
|
||||
var keys = new List<Keyframe>();
|
||||
for (int i = 0; i <= 48; i++) keys.Add(new Keyframe(i / 48f, i % 2 == 0 ? 1f : 0f));
|
||||
line.widthCurve = new AnimationCurve(keys.ToArray());
|
||||
}
|
||||
else line.widthCurve = AnimationCurve.Constant(0, 1, 1);
|
||||
}
|
||||
private void OnDestroy() { if (lineMaterial) Destroy(lineMaterial); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2b3836b8353afbe43a3e23ef62a45977
|
||||
@@ -0,0 +1,122 @@
|
||||
using System.Collections;
|
||||
using TMPro;
|
||||
using UnityEngine;
|
||||
using UnityEngine.EventSystems;
|
||||
using UnityEngine.UI;
|
||||
|
||||
namespace DepthsOfGreed.HandbookUI
|
||||
{
|
||||
public sealed class TowerCardView : MonoBehaviour, IPointerClickHandler, IBeginDragHandler, IDragHandler, IEndDragHandler
|
||||
{
|
||||
public HandbookTowerEntry Entry { get; private set; }
|
||||
private BuildMenuController menu;
|
||||
private GameObject front, back;
|
||||
private TMP_Text nameText, costText, statsText, infoText;
|
||||
private Coroutine animation;
|
||||
private Vector3 originalScale;
|
||||
private bool showingBack, dragged;
|
||||
private Image icon;
|
||||
private Sprite placeholderSprite;
|
||||
private Color placeholderColor;
|
||||
|
||||
public void Initialize(BuildMenuController owner)
|
||||
{
|
||||
menu = owner;
|
||||
front = transform.Find("Front").gameObject;
|
||||
back = transform.Find("Back").gameObject;
|
||||
nameText = front.transform.Find("NameText").GetComponent<TMP_Text>();
|
||||
costText = front.transform.Find("CostText").GetComponent<TMP_Text>();
|
||||
statsText = front.transform.Find("StatsText").GetComponent<TMP_Text>();
|
||||
infoText = back.transform.Find("InfoText").GetComponent<TMP_Text>();
|
||||
icon = front.transform.Find("TowerIcon").GetComponent<Image>();
|
||||
placeholderSprite = icon.sprite;
|
||||
placeholderColor = icon.color;
|
||||
originalScale = transform.localScale;
|
||||
foreach (var text in GetComponentsInChildren<TMP_Text>(true))
|
||||
{
|
||||
text.raycastTarget = false;
|
||||
text.color = Color.black;
|
||||
text.enableAutoSizing = true;
|
||||
text.fontSizeMin = 14;
|
||||
text.fontSizeMax = text.fontSize;
|
||||
}
|
||||
SetBack(false, true);
|
||||
}
|
||||
|
||||
public void Bind(HandbookTowerEntry entry)
|
||||
{
|
||||
Entry = entry;
|
||||
nameText.text = entry.displayName;
|
||||
costText.text = "Kosten: " + entry.energyCost + " Energie (Test)";
|
||||
statsText.text = entry.summary;
|
||||
infoText.text = entry.description;
|
||||
icon.sprite = entry.icon ? entry.icon : placeholderSprite;
|
||||
icon.color = entry.icon ? Color.white : placeholderColor;
|
||||
icon.preserveAspect = true;
|
||||
}
|
||||
|
||||
public void OnPointerClick(PointerEventData data)
|
||||
{
|
||||
if (data.button == PointerEventData.InputButton.Left && !data.dragging && !dragged)
|
||||
menu.ToggleCard(this);
|
||||
dragged = false;
|
||||
}
|
||||
|
||||
public void OnBeginDrag(PointerEventData data)
|
||||
{
|
||||
dragged = true;
|
||||
if (data.button == PointerEventData.InputButton.Left && !showingBack && menu.Placement)
|
||||
menu.Placement.Begin(Entry, data.position);
|
||||
}
|
||||
public void OnDrag(PointerEventData data)
|
||||
{
|
||||
if (menu.Placement) menu.Placement.Move(data.position);
|
||||
}
|
||||
public void OnEndDrag(PointerEventData data)
|
||||
{
|
||||
if (menu.Placement) menu.Placement.End(data.position);
|
||||
dragged = false;
|
||||
}
|
||||
|
||||
public void SetBack(bool showBack, bool instant = false)
|
||||
{
|
||||
showingBack = showBack;
|
||||
if (animation != null) StopCoroutine(animation);
|
||||
animation = null;
|
||||
if (instant || !isActiveAndEnabled)
|
||||
{
|
||||
transform.localScale = originalScale;
|
||||
front.SetActive(!showBack);
|
||||
back.SetActive(showBack);
|
||||
}
|
||||
else animation = StartCoroutine(Flip(showBack));
|
||||
}
|
||||
|
||||
private IEnumerator Flip(bool showBack)
|
||||
{
|
||||
float startingY = transform.localScale.y;
|
||||
const float halfDuration = 0.09f;
|
||||
for (float elapsed = 0; elapsed < halfDuration; elapsed += Time.unscaledDeltaTime)
|
||||
{
|
||||
transform.localScale = new Vector3(originalScale.x, Mathf.Lerp(startingY, 0.02f, elapsed / halfDuration), originalScale.z);
|
||||
yield return null;
|
||||
}
|
||||
front.SetActive(!showBack);
|
||||
back.SetActive(showBack);
|
||||
for (float elapsed = 0; elapsed < halfDuration; elapsed += Time.unscaledDeltaTime)
|
||||
{
|
||||
transform.localScale = new Vector3(originalScale.x, Mathf.Lerp(0.02f, originalScale.y, elapsed / halfDuration), originalScale.z);
|
||||
yield return null;
|
||||
}
|
||||
transform.localScale = originalScale;
|
||||
animation = null;
|
||||
}
|
||||
|
||||
private void OnDisable()
|
||||
{
|
||||
if (animation != null) StopCoroutine(animation);
|
||||
animation = null;
|
||||
transform.localScale = originalScale;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 160e7a510a18f0d48afcb4c03a705c0a
|
||||
Reference in New Issue
Block a user