From ec7f833db710aec7c4adc169a7d2d852b5b0f507 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Tobias=20Sch=C3=B6ner?= <tobias.stonehead@gmail.com>
Date: Fri, 20 Jan 2023 16:30:43 +0100
Subject: [PATCH] feat: FactExplorer will now try to overlay mainFact on
 clicked Fact

if a part of FactExplorer would be out of screen bounds it will be clamped to be fully visible
---
 .../Scripts/UI/FactExplorer/FactExplorer.cs   | 19 ++++++++++++++++++-
 .../UI/FactExplorer/OpenFactExplorer.cs       |  2 +-
 2 files changed, 19 insertions(+), 2 deletions(-)

diff --git a/Assets/Scripts/UI/FactExplorer/FactExplorer.cs b/Assets/Scripts/UI/FactExplorer/FactExplorer.cs
index 199362a7..439eaf68 100644
--- a/Assets/Scripts/UI/FactExplorer/FactExplorer.cs
+++ b/Assets/Scripts/UI/FactExplorer/FactExplorer.cs
@@ -33,7 +33,7 @@ private void Update()
         DestroyIfClickedOutside();
     }
 
-    public void Initialize(Fact fact)
+    public void Initialize(Fact fact, Vector3 factPosition)
     {
         mainFact = fact;
         parentFacts = GetParentFacts();
@@ -43,6 +43,8 @@ public void Initialize(Fact fact)
         Debug.Log($"Children of {mainFact.Label}: {string.Join(", ", childFacts.Select(cf => cf.Label))}");
 
         UpdateFactExplorerUI();
+
+        MoveToPreferredPosition(factPosition);
     }
     #endregion UnityMethods
 
@@ -94,6 +96,21 @@ private void DestroyIfClickedOutside()
             Destroy(gameObject);
         }
     }
+
+    private void MoveToPreferredPosition(Vector3 prefPos)
+    {
+        LayoutRebuilder.ForceRebuildLayoutImmediate(transform.GetComponent<RectTransform>());
+        // calculate opimal position
+        var deltaPos = mainFactUI.position - prefPos;
+        transform.position -= deltaPos;
+
+        // clamp position, so that no parts of the FactExplorer are out of screen
+        RectTransform feRect = GetComponent<RectTransform>();
+        Vector2 apos = feRect.anchoredPosition;
+        apos.x = Mathf.Clamp(apos.x, 0, Screen.width - feRect.sizeDelta.x);
+        apos.y = Mathf.Clamp(apos.y, -Screen.height + feRect.sizeDelta.y, 0);
+        feRect.anchoredPosition = apos;
+    }
     #endregion Implementation
 
     #region Spawner
diff --git a/Assets/Scripts/UI/FactExplorer/OpenFactExplorer.cs b/Assets/Scripts/UI/FactExplorer/OpenFactExplorer.cs
index 8e50e2a1..ddd11571 100644
--- a/Assets/Scripts/UI/FactExplorer/OpenFactExplorer.cs
+++ b/Assets/Scripts/UI/FactExplorer/OpenFactExplorer.cs
@@ -21,7 +21,7 @@ public void OnPointerClick(PointerEventData eventData)
             var fact = transform.GetComponent<FactWrapper>().fact;
 
             factExplorer = Instantiate(factExplorerPrefab.transform, Input.mousePosition, Quaternion.identity, parent);
-            factExplorer.GetComponent<FactExplorer>().Initialize(fact);
+            factExplorer.GetComponent<FactExplorer>().Initialize(fact, transform.position);
         }
     }
 }
-- 
GitLab