ugui制作伸缩菜单

 图片
制作一个类似与这种格式的菜单,可以伸缩滑动的。
今天正好项目需要用到类似功能,所以尝试了一下,做出如下的效果
图片

图片

虽然只是一个思路,但是可以扩展。
声明一个object物体,为but,通过GetComponent<RectTransform>().anchoredPosition,将其赋值移动到目标位置
下面是UGUI的cs代码。 
 using UnityEngine;

using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
 
public class UGUI : MonoBehaviour {
    public Image image;
    public bool image_bool;
    public GameObject but;
 
// Use this for initialization
void Start () {
        image_bool = false;
}
 
// Update is called once per frame
void Update () {
 
}
 
    public void button()
    {
        image_bool = !image_bool;
        image.gameObject.SetActive(image_bool);
        but.GetComponent<RectTransform>().anchoredPosition = new Vector2(27, -85);
    }
}

这边button代码
下面注释部分是采用碰撞box collider2D,获取imgage,和下面button(1)碰撞事件,获取rectTransform.anchoredPosition相对的坐标,然后将其挤开,从而实现移动的效果,有兴趣的可以试试下面这种,需要在image和button(1)添加box collider2D盒子碰撞器以及rigidbody 2D事件,另外千万不要忘记了Constranints里面的 freeze position 将x 和y勾选上噢。
图片 

下面是完整代码,其余绑定事件什么的我就不贴出来了阿,可以自行网上参考。
using UnityEngine;
using System.Collections;
 
public class button : MonoBehaviour {
public Vector2 zi_v2;
 
    public bool ziji_bool;
 
// Use this for initialization
void Start () {
        ziji_bool = false;
        zi_v2 = new Vector2(GetComponent<RectTransform>().anchoredPosition.x,GetComponent<RectTransform>().anchoredPosition.y);
}
 
// Update is called once per frame
void Update () {
        if (!GameObject.Find("Canvas").GetComponent<UGUI>().image_bool) {
            hf();
        }
}
 
    public void hf() {
        GetComponent<RectTransform>().anchoredPosition = zi_v2;
    }
    //void OnCollisionEnter2D(Collision2D coll)
    //{
    //    Debug.Log(coll.gameObject.name);
    //    RectTransform coll_name = GameObject.Find(coll.gameObject.name).GetComponent<RectTransform>();
    //    //GetComponent<RectTransform>().anchoredPosition = new Vector2(GetComponent<RectTransform>().anchoredPosition.x, coll_name.sizeDelta.y);
    //    GetComponent<RectTransform>().anchoredPosition = new Vector2(GetComponent<RectTransform>().anchoredPosition.x, GetComponent<RectTransform>().anchoredPosition.y);
    //    ziji_bool = true;
    //}
}
posted @ 2016-09-05 20:23  智取  阅读(5117)  评论(0编辑  收藏  举报