摇杆代码(委托+事件)

来源:互联网 发布:微博刷转发软件 编辑:程序博客网 时间:2024/05/17 09:32
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;




public class JoyStick : MonoBehaviour,IPointerDownHandler,IPointerUpHandler,IDragHandler
{


public delegate void JoyStickBegin(Vector2 pos);
public delegate void JoyStickDrag(Vector2 pos);
public delegate void JoyStickEnd();


public event JoyStickBegin OnBeginHandler;
public event JoyStickDrag OnDragHandler;
public event JoyStickEnd OnEndHandler;



public float radius = 50f;
public float resetspeed = 5f;
public bool isTouched = false;


private RectTransform mTran;
private Vector2 startPos;
private Vector2 touchedAxis;
private Vector3 worldPosition; 


public Vector2 TouchedAxis
{
get{ 

if (touchedAxis.magnitude < radius) 
{
return touchedAxis.normalized / radius;
}


return touchedAxis.normalized;
}
}


void Start()        //获取摇杆初始位置
{
mTran = this.GetComponent<RectTransform> ();
startPos = mTran.anchoredPosition;
}


public void OnPointerDown(PointerEventData data)
{
isTouched = true;
touchedAxis = GetJoyStickAxis (data);
if (this.OnBeginHandler != null) 
{
this.OnBeginHandler (TouchedAxis);
}
}


public void OnPointerUp(PointerEventData data)
{
isTouched = false;
mTran.anchoredPosition = startPos;
touchedAxis = Vector2.zero;
if (this.OnEndHandler != null) 
{
this.OnEndHandler ();
}
}


public void OnDrag (PointerEventData data)
{
touchedAxis = GetJoyStickAxis (data);
if (this.OnDragHandler != null) 
{
this.OnDragHandler (TouchedAxis);
}
}


void Update()
{
if (isTouched && touchedAxis.magnitude >= radius) 
{
if (this.OnDragHandler != null) 
{
this.OnDragHandler (TouchedAxis);
}
}


if (mTran.anchoredPosition.magnitude > startPos.magnitude)
{
mTran.anchoredPosition -= TouchedAxis * Time.deltaTime * resetspeed;
}
}


private Vector2 GetJoyStickAxis(PointerEventData data)     
{                                                                             //获取手指位置的世界坐标      
        
if (RectTransformUtility.ScreenPointToWorldPointInRectangle (mTran, data.position, data.pressEventCamera, out worldPosition))         
mTran.position = worldPosition;                               //获取摇杆的偏移量        
Vector2 touchAxis = mTran.anchoredPosition-startPos;         //摇杆偏移量限制        
if(touchAxis.magnitude >= radius)          
{             
touchAxis = touchAxis.normalized * radius;            
mTran.anchoredPosition = touchAxis;        
}         
return touchAxis;    



}

0 0