【小松教你手游开发】【系统模块开发】父节点下的各个子节点居中摆放

有过一个需求需要一个item,两个item,三个item(不一定有多少个子节点)不同情况都要居中

有两个方法解决:

1.只需要在uiscrollview上的resetPosition 设为0.5,调一下resetPosition自动居中

2.如果本身在uiScrollview上就不能这么用了,两个uiscrollview不能重叠嘛。

所以写了个脚本负责计算每个子节点的localposition。

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class CenterChildTransfroms
{
    UIAnchor m_anchor;
    private Transform m_transform;
    private GameObject m_containerGameObject;
    private float m_spacing;

    public CenterChildTransfroms(Transform transform, GameObject containerGameObject,Camera camera, float spacing =0)
    {
        m_transform = transform;
        m_containerGameObject = containerGameObject;
        m_spacing = spacing;

        m_anchor = m_transform.GetComponent<UIAnchor>();
        if (m_anchor == null)
            m_anchor = m_transform.gameObject.AddComponent<UIAnchor>();
        m_anchor.uiCamera = camera;
        m_anchor.container = containerGameObject;
        m_anchor.side = UIAnchor.Side.Center;
        m_anchor.enabled = false;
    }

    public void RepositionChildTransfroms()
    {
        float totalWidth = 0;
        List<Transform> childTrans = new List<Transform>();
        List<float> childTransBoundSizeX = new List<float>();
        foreach (Transform t in m_transform)
        {
            if(t.gameObject.activeSelf)
            {
                childTrans.Add(t);
                float width = (NGUIMath.CalculateRelativeWidgetBounds(t).size.x * t.localScale.x) + m_spacing;
                totalWidth += width;
                childTransBoundSizeX.Add(width);
            } 
        }

        if(childTrans.Count > 0)
        {
            //先计算好第一个transform坐标
            childTrans[0].localPosition = new Vector3((-totalWidth / 2 + childTransBoundSizeX[0] / 2), childTrans[0].localPosition.y, childTrans[0].localPosition.z);

            for(int i =1;i<childTrans.Count;i++)
            {
                float lastTransBoundX = childTransBoundSizeX[i - 1] / 2;
                float transBoundX = childTransBoundSizeX[i] / 2;

                childTrans[i].localPosition = new Vector3(childTrans[i - 1].localPosition.x + lastTransBoundX + transBoundX , childTrans[i].localPosition.y,childTrans[i].localPosition.z);
            }
        }
        CenterTransform();
    }


    public void CenterTransform()
    {
        m_anchor.enabled = true;
    }
}

这里可以看到使用前是需要传递父节点transform,居中在哪个GameObject的那个gameObject,传入所属UIcamera,和每个子节点之间间隙。

其实也就是在父节点上添加一个锚点UIAnchor,把需要的参数(cotainerGameObject,Camera)塞进去.

计算时先计算总宽,算出并摆放第一个transform的localPosition,之后根据这个坐标进行一个个计算


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值