效果:
1.首先 Input.mousePosition 得到的是鼠标点到屏幕上的像素点坐标,这个坐标的(0,0,0)位置是屏幕的左下角,如果你点击屏幕中间,得到的是 (Screen.width / 2,
。Screen.height / 2,0
)
2.再说UI,
① 如果UI对齐方式是下图,它在屏幕中间时,为(0,0),如果要让它跟随鼠标位置,鼠标点了屏幕中间,它就得在屏幕中间,鼠标Input.mousePosition是 (Screen.width / 2,
,赋值的时候就要如下写法:Screen.height / 2,0
)
UI.anchoredPosition3D = new Vector3(Input.mousePosition.x - Screen.width / 2
, Input.mousePosition.y - Screen.
/ 2, 0);height
② 如果UI对齐方式是下图,它在屏幕中间时,为(Screen.width / 2,
Screen.height / 2,0
),与Input.mousePosition一致,此时复制方式如下:
UI.anchoredPosition3D = Input.mousePosition;
因为我做的是点击空白处执行某方法,所以我在整个Canvas上加了个大的collider,和canvas一样大:
然后要让相机和canvas正对,这样collider才能挡住鼠标点击屏幕任何位置发射的射线;
然后是进度条:
脚本:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class LongPressBackUp : MonoBehaviour { //计时 bool isBack; //是否已经执行过返回 bool isTime; //是否开始计时 float time; //长按持续的时间 //返回退出进度条 public RectTransform progressUI; public Image progressImage; private void Start() { progressUI.gameObject.SetActive(false); } void Update() { LongPressTime(); } /// <summary> /// 计时(长按0.5s显示进度条UI,再持续1s执行返回方法) /// </summary> void LongPressTime() { if (!isTime) return; time += Time.deltaTime; progressImage.fillAmount = (time - 0.5f) / 1f; //长按0.5s之后,进度条才开始走 if (time > 1.5f) //长按1.5s后执行返回方法,并重置 { BackUp(); progressUI.gameObject.SetActive(false); isBack = true; isTime = false; } else if (time > 0.5f) //长按0.5s之后,显示返回UI { progressUI.gameObject.SetActive(true); } } #region 长按 private void OnMouseDrag() { Debug.Log("进入"); if (isBack) return; isTime = true; //UI跟随鼠标移动 progressUI.anchoredPosition3D = Input.mousePosition; } private void OnMouseUp() { progressUI.gameObject.SetActive(false); isTime = false; time = 0f; isBack = false ; } #endregion /// <summary> /// 返回 /// </summary> void BackUp() { Debug.Log("返回"); //Application.Quit(); } }
项目连接:https://download.csdn.net/download/qq_15017279/20082635