Unity3D - 将UI对象移动到屏幕中心,同时保持其父节点

时间:2017-07-25 17:59:35

标签: c# unity3d unity3d-gui

我有一个UI图像,该图像是RectTransform容器的父级,该容器是UI面板的父级,该面板是Canvas的父级。

我希望能够将此UI图像移动到屏幕的中心(即画布),同时保留父级层次结构。我的目标是将UI图像从中心动画到现在的位置。你能告诉我这段代码的样子吗?

enter image description here

2 个答案:

答案 0 :(得分:1)

要回答原始问题,您可以使用以下网址将UICell放在屏幕中央:

private RectTransform rect;

void Start() 
{
    rect = GetComponent<RectTransform>();
    rect.position = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width / 2, Screen.height / 2, 10));
}

然后有几种方法可以将单元格移动到所需的目标位置。一种方法是使用Vector2.Lerp。但是,由于矩形变换父母层次结构的性质,定位会变得有点复杂 - 下面是 可以完成移动的示例。

float t;

void Update()
{
    t += Time.deltaTime;
    rect.localPosition = Vector2.Lerp(rect.localPosition, new Vector2(0, 0), t/3f);
}

答案 1 :(得分:0)

最终工作的是将UI Image的父级更改为画布,将UI图像移动到画布的中间(即屏幕),并恢复原始UI Image父关系。从那里,我只需要动画到原来的本地位置。

var rectTransform = gameObject.GetComponent<RectTransform>();
var canvasRendererRectTransform = gameObject.transform.parent.parent.parent.GetComponent<RectTransform>();

rectTransform.SetParent(canvasRendererRectTransform);
rectTransform.localPosition = Camera.main.ScreenToViewportPoint(Vector3.one * 0.5f);
rectTransform.SetParent(gridRendererRectTransform);