Unity3D - Move UI object to center of screen while maintaining its parenting

蹲街弑〆低调 提交于 2019-12-24 07:10:06

问题


I have an UI image that is parented to a RectTransform container, which is parented to a UI panel, which is parented to a Canvas.

I want to be able to move this UI image to the center of the screen (ie. canvas) while leaving the parenting hierarchy. My goal is to animate the UI image from the center to where it is now. Can you please let me know what this code would look like?


回答1:


To answer your original question, you can place the UICell at the center of the screen using:

private RectTransform rect;

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

There are then several ways to move the cell to the desired destination. One method would be to use Vector2.Lerp. However, due the nature of your rectangular transform parental hierarchy, things will get a little complicated with the positioning - below is an example of how you could accomplish the movement.

float t;

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



回答2:


What ended up working was changing the parent of the UI Image to the canvas, move the UI image to the middle of the canvas (ie. screen), and reinstate the original UI Image parent relationship. From there, I just needed to animate to the original local position.

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);


来源:https://stackoverflow.com/questions/45310558/unity3d-move-ui-object-to-center-of-screen-while-maintaining-its-parenting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!