unity鼠标移动到指定区域自动拉出菜单框(附源码)(方法一)

public class Menumove : MonoBehaviour/*, IPointerEnterHandler, IPointerExitHandler*/
{
    /// <summary>
    /// 鼠标位置
    /// </summary>
    Vector2 a;
    [Range(0.0f, 10.0f)]
    public float moveSpeed = 0.1f;//图片移动速度
    /// <summary>
    /// 显示上拉框的位置
    /// </summary>
    private Vector2 showupPos;
    /// <summary>
    /// 隐藏上拉框的位置
    /// </summary>
    private Vector2 hideupPos;
    /// <summary>
    /// 记录上拉框图片位置
    /// </summary>
    private RectTransform _upTransfrom;
    private bool _isShow;
    float timeDiff = 1;
    float speed = 0.05f;
    int w;
    int h;
    void Start()
    {
        _upTransfrom = GameObject.Find("上拉框名").gameObject.GetComponent<RectTransform>();
        showupPos = _upTransfrom.anchoredPosition;//初始显示位置
        hideupPos = new Vector2(showupPos.x, showupPos.y + 300);//隐藏时移动到的位置,垂直移动
                                                   
    }
    void Update()
    {
        Vector2 a = Input.mousePosition;
        w = Screen.width;
        h = Screen.height;
        if (a.y > (h - h / 9))//上拉框出现
        {
            if (a.x > w / 8 && a.x < (w - w / 8))
            {
                timeDiff -= speed;
                if (timeDiff <= -0.5f)
                {
                    timeDiff = -0.5f;
                }
                Vector2 currentPos = Vector2.Lerp(showupPos, hideupPos, timeDiff);
                _upTransfrom.anchoredPosition = currentPos;
            }
        }
        if(a.y < (h - (2 * h / 9)) || a.x < w / 8 || a.x > w - w / 8)
        {
            //Debug.Log("上拉狂消失");
            timeDiff += speed;
            if (timeDiff >= 1.5f)
            {
                timeDiff = 1.5f;
            }
            Vector2 currentPos = Vector2.Lerp(showupPos, hideupPos, timeDiff);
            _upTransfrom.anchoredPosition = currentPos;
        }

通过比例来动态判断鼠标是否移动到唤出隐藏栏的位置,代码只写了上拉框的控制脚本,左边隐藏栏同理。

这是通过判断鼠标坐标来实现的,还有一种方法在另一篇文章

隐藏栏

猜你喜欢

转载自blog.csdn.net/qq_52058429/article/details/126148940