用代码写一个虚拟摇杆
找到一个以前跟老师学时,写的一个虚拟摇杆脚本,希望可以对大家有所借鉴。
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class Joystick : MonoBehaviour,IPointerDownHandler,IPointerUpHandler,IDragHandler{ /// <summary> /// 虚拟摇杆的底图 /// </summary> public Image backGroundImage; /// <summary> /// 虚拟摇杆显示手指按下/移动区域 /// </summary> public Image pointerImage; /// <summary> /// 虚拟摇杆朝哪移动 /// </summary> public Vector3 moveForwad; /// <summary> /// 虚拟摇杆旋转 /// </summary> public Vector3 rotationForwad; // Use this for initialization void Start () { } // Update is called once per frame void Update () { }/// <summary> /// 鼠标/手指点下移动相应处理 /// </summary> /// <param name="eventData"></param> public void pointerMove(PointerEventData eventData) { //我们的摇杆效果 Vector2 pos;//虚拟摇杆中心位置 if (RectTransformUtility.ScreenPointToLocalPointInRectangle (backGroundImage.rectTransform,//底图 eventData.position,//鼠标或者手指在屏幕上的位置 eventData.enterEventCamera,//ui摄像机 out pos )){ //我们将POS的X/Y进行计算,计算出来相对于宽和高比例是多少 pos.x = pos.x / backGroundImage.rectTransform.sizeDelta.x; pos.y = pos.y / backGroundImage.rectTransform.sizeDelta.y; Debug.Log("pos=" + pos); //将取值范围进行调整 pos.x = pos.x * 2 - 1;//取值范围改为[-1,1] pos.y = pos.y * 2 - 1; Debug.Log("pos=" + pos*10); if (pos.magnitude > 1) { pos.Normalize(); } //给中心图片进行位置设定 pointerImage.rectTransform.anchoredPosition = //pos; new Vector2( pos.x * (backGroundImage.rectTransform.sizeDelta.x / 2) , pos.y * (backGroundImage.rectTransform.sizeDelta.y / 2)); //移动 moveForwad = new Vector3(pos.x, 0, pos.y); //旋转 rotationForwad = new Vector3(pos.x, 0, pos.y); } } /// <summary> /// 手指或者鼠标按下事件 /// </summary> /// <param name="eventData"></param> public void OnPointerDown(PointerEventData eventData) { Debug.Log("手指按下"); pointerMove(eventData); } /// <summary> /// 手指或者鼠标抬起事件 /// </summary> /// <param name="eventData"></param> public void OnPointerUp(PointerEventData eventData) { Debug.Log("手指抬起"); pointerImage.rectTransform.anchoredPosition = Vector2.zero;//鼠标或者手指抬起后中心点回去 moveForwad= Vector3.zero; } /// <summary> /// 手指或者鼠标拖拽事件 /// </summary> /// <param name="eventData"></param> public void OnDrag(PointerEventData eventData) { Debug.Log("手指拖拽"); pointerMove(eventData); } }
比较复杂,也是很久以前写的了,耐心看哈!一起学习。