using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class YAOGAN : MonoBehaviour { private Vector2 firstPos;//点击时候的位置 private Vector2 lastPos;//上一个位置 private Vector2 currentPos;//下一个位置 public Image img;// public Image img2;// float timer; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void OnGUI() { if (Event.current.type == EventType.MouseDown) {//滑动开始 firstPos = Event.current.mousePosition;//这个位置就是负责产生摇杆的 lastPos = Event.current.mousePosition; currentPos = Event.current.mousePosition; timer = 0; //TODO click event Debug.Log("Click begin && Drag begin"); } if (Event.current.type == EventType.MouseDrag) {//滑动过程 currentPos = Event.current.mousePosition; // Debug.Log(currentPos+"点击的当前位置 屏幕高度" + Screen.height); if (timer == 0) { img.gameObject.SetActive(true); img2.gameObject.SetActive(true); currentPos.y = Screen.height - currentPos.y;//位移位置 img.transform.position = currentPos;//位移位置 } timer += Time.deltaTime; Vector3 offset; offset = currentPos - firstPos;//当前位置-第一次位置 offset.y = -offset.y;//取负数 offset /= 3f; if (offset.magnitude > 100f) { Debug.Log("大于100"); img2.transform.position = img.transform.position + offset / offset.magnitude * 100f; } else img2.transform.position = img.transform.position + offset; lastPos = currentPos; } if (Event.current.type == EventType.MouseUp) {//滑动结束 // currentVector = slideVector.nullVector; Debug.Log("Click over && Drag over"); firstPos = Vector2.zero; timer = 0; img2.transform.position = img.transform.position; img.gameObject.SetActive(false); img2.gameObject.SetActive(false); } } }
被控制的对象通过获取ui位置差进行相关移动
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerTransform : MonoBehaviour { public Transform pos1, pos2; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (pos1.position.x - pos2.position.x == 0 || pos1.position.y - pos2.position.y == 0) { return; } this.transform.position += new Vector3((pos2.position.x - pos1.position.x)/20,0f,( pos2.position.y - pos1.position.y)/20); } }
上面的摇杆放到手机上炸了。重新写了一个。已经考虑到屏幕适配