I’m having a bit of a problem converting between coordinate systems at different levels of UI hierarchy and I was wondering if you could help me.
I’m trying to write a technology tree and I’ve got it working providing the anchors are arranged very specifically and the elements that make up the technology tree are all children of the tree container.
I’d like it to be a bit more flexible than that and at the heart of it seems to be a problem writing a generic function that will convert from child to parent UI elements and back again.
One part of it seems to be the way anchors work. As far as I understand it, I think anchors are the points in the parent object’s space that are where the anchorPosition vector works from, with differences for strech anchors. How that fits all together, I’m not too sure.
These are the functions I’ve got working for one layer. Many thanks for any help.
public static Vector2 TransformMyToAncestorSpace( GameObject me, GameObject ancestor, Vector2 point )
{
Vector2 ret = point;
GameObject GO=me, parentGO=Hierarchy.Parent(GO);
RectTransform RT, parentRT;
while (GO != ancestor && parentGO != null) {
Debug.Log ("TMtAS: Debug: ");
RT = GO.GetComponent<RectTransform> ();
parentRT = parentGO.GetComponent<RectTransform> ();
//Vector2 pos;
if (parentRT.anchorMax == parentRT.anchorMin) {
ret = RT.anchoredPosition + ret + new Vector2 (parentRT.sizeDelta.x * parentRT.anchorMin.x, parentRT.sizeDelta.y * parentRT.anchorMin.y);
} else {
ret = RT.anchoredPosition + ret + parentRT.pivot;
}
//ret = ret + RT.anchoredPosition;
GO = Hierarchy.Parent (GO);
parentGO = Hierarchy.Parent (GO);
}
if (GO == ancestor)
return ret;
else
return default(Vector2);
}
public static Vector2 TransformAncestorToMySpace( GameObject ancestor, GameObject me, Vector2 point )
{
Vector2 ret = point;
GameObject GO=me, parentGO=Hierarchy.Parent(GO);
RectTransform RT, parentRT;
while (GO != ancestor && parentGO != null) {
Debug.Log ("TAtMS: Debug");
RT = GO.GetComponent<RectTransform> ();
parentRT = parentGO.GetComponent<RectTransform> ();
if (parentRT.anchorMax == parentRT.anchorMin) {
ret = -RT.anchoredPosition + ret - new Vector2 (parentRT.sizeDelta.x * parentRT.anchorMin.x, parentRT.sizeDelta.y * parentRT.anchorMin.y);
} else {
ret = -RT.anchoredPosition + ret - parentRT.pivot;
}
//ret = ret - RT.anchoredPosition;
GO = Hierarchy.Parent (GO);
}
if (GO == ancestor)
return ret;
else
return default(Vector2);
}
I’ve made a script that reverse engineers the unity’s rect transforms when you’re changing how they are parented. Only handles th normal pivot presets.
Hope it helps for anyone who had a go at this.
P.S: m_MidAnchor = Vector2(0.5,0.5)
private Rect TransformToAncestorSpace(RectTransform selectable, RectTransform ancestor)
{
Vector2 position = selectable.anchoredPosition;
string debugString = selectable.name +"