我个人认为此方法相比于第一种更简洁一点
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Smoothmove : MonoBehaviour
{
[Range(0.0f, 10.0f)]//***
[HideInInspector]
public float moveSpeed = 2.0f;//图片移动速度
/// <summary>
/// 显示上拉框的位置
/// </summary>
private Vector2 showupPos;
/// <summary>
/// 隐藏上拉框的位置
/// </summary>
private Vector2 hideupPos;
/// <summary>
/// 记录上拉框图片位置
/// </summary>
private RectTransform _upTransfrom;
private bool _isShow;
/// <summary>
/// 显示左拉框的位置
/// </summary>
private Vector2 showleftPos;
/// <summary>
/// 隐藏左拉框的位置
/// </summary>
private Vector2 _hideleftPos;
/// <summary>
/// 记录左拉框图片位置
/// </summary>
private RectTransform _leftTransfrom;
/// <summary>
/// 判断是否移动到上面的菜单栏区域
/// </summary>
bool _up;
bool _left;
private RectTransform uparea;
private RectTransform leftarea;
void Start()
{
uparea = GameObject.Find("moveup").gameObject.GetComponent<RectTransform>();
leftarea = GameObject.Find("moveleft").gameObject.GetComponent<RectTransform>();
_up = false;
_left=false;
_upTransfrom = GameObject.Find("Scroll View H").gameObject.GetComponent<RectTransform>();//因为代码挂在上拉框上,直接获取上拉框初始位置
showupPos = _upTransfrom.anchoredPosition;//初始显示位置
hideupPos = new Vector2( showupPos.x,showupPos.y + 300);//隐藏时移动到的位置,垂直移动
//_isShow = false;
_leftTransfrom = GameObject.Find("di").gameObject.GetComponent<RectTransform>();//di是左拉框
showleftPos = _leftTransfrom.anchoredPosition;//初始显示位置
_hideleftPos = new Vector2(showleftPos.x -300, showleftPos.y);//隐藏时移动到的位置,水平移动
}
void Update()
{
_up = RectTransformUtility.RectangleContainsScreenPoint(uparea, Input.mousePosition);
_left = RectTransformUtility.RectangleContainsScreenPoint(leftarea, Input.mousePosition);
if (_up)
{
ShowMenu();
}
if (_left)
{
Showleft();
}
}
/// <summary>
/// 调用显示上侧携程,可在别处调用此函数来显示菜单
/// </summary>
public void ShowMenu()
{
StartCoroutine(Appear());
}
/// <summary>
/// 显示上侧菜单
/// </summary>
/// <returns></returns>
IEnumerator Appear()
{
float time = Time.time;
float timeDiff = 0;
while (timeDiff < 1)
{
timeDiff = (Time.time - time) * moveSpeed;
Vector2 currentPos = Vector2.Lerp(showupPos, hideupPos, timeDiff);
_upTransfrom.anchoredPosition = currentPos;
yield return new WaitForEndOfFrame();
}
//_isShow = true;
}
/// <summary>
/// 调用显示左拉框的携程
/// </summary>
public void Showleft()
{
StartCoroutine(Appearleft());
}
/// <summary>
/// 显示左拉框的携程
/// </summary>
/// <returns></returns>
IEnumerator Appearleft()
{
float time = Time.time;
float timeDiff = 0;
while (timeDiff < 1)
{
timeDiff = (Time.time - time) * moveSpeed;
Vector2 currentPos = Vector2.Lerp(showleftPos, _hideleftPos, timeDiff);
_leftTransfrom.anchoredPosition = currentPos;
yield return new WaitForEndOfFrame();//***
}
_isShow = true;
}
}
这是通过检测UI区域来实现的,还有一种方法在另一篇文章
20220803_211104