1,创建一个位置事件参数类UIjoyEventArge
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
ublic class UIjoyEventArge : IEventArgs { public static int UIjoyEventArgeId = 100;//不重复Id(暂时固定死) public int Id { get { return UIjoyEventArgeId; } } public Vector3 Data; }
2、处理拖拽事件UIjoysticks
public class UIjoysticks : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler { public float r; public RectTransform backGroud; EventManager eventManager; UIjoyEventArge uIjoyEventArge; protected void Start() { r = backGroud.sizeDelta.x * 0.5f; eventManager = FactoryManager.CreatClass<EventManager>(); uIjoyEventArge = FactoryManager.CreatClass<UIjoyEventArge>(); } public void OnDrag(PointerEventData eventData) { Vector3 mousPos = Vector3.zero; if (RectTransformUtility.ScreenPointToWorldPointInRectangle(transform as RectTransform, eventData.position, eventData.enterEventCamera, out mousPos)) { transform.position = mousPos; } if (transform.localPosition.magnitude > r) { transform.localPosition = Vector3.ClampMagnitude(transform.localPosition, r); } } public void OnBeginDrag(PointerEventData eventData) { isDrag = true; } bool isDrag = false; public void OnEndDrag(PointerEventData eventData) { transform.localPosition = Vector3.zero; isDrag = false; } void Update() { if (isDrag) { UIjoyEventArge uIjoyEventArge = FactoryManager.CreatEventClass<UIjoyEventArge>(); uIjoyEventArge.Data = transform.localPosition.normalized * Time.deltaTime; eventManager.Fire(this,uIjoyEventArge); } } }
3,接听事件
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
public class Cube : MonoBehaviour { public float speed; // Start is called before the first frame update void Start() { EventManager eventManager =FactoryManager.CreatClass<EventManager>(); eventManager.Subscribe(UIjoyEventArge.UIjoyEventArgeId, (obj,args) => { UIjoyEventArge uIjoyEventArge = args as UIjoyEventArge; transform.Translate(uIjoyEventArge.Data * speed); }); } }
4,完成!