Unity中实现摇杆功能

虽然现在在Unity中实现摇杆有,Easy Touch来帮你完成,今天我就来给大家分享手动敲代码实现摇杆功能

下面开始上代码:

using UnityEngine; using System.Collections; using UnityEngine.UI; using UnityEngine.EventSystems;

public class MyJoystick : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IDragHandler, IEndDragHandler { public static MyJoystick instance;

public Image dayuan;
public Image xiaoyuan;

public Vector2 direction;

void Awake()
{
    if (instance == null)
    {
        instance = this;
    }
}
// Use this for initialization
void Start()
{
    dayuan.color = new Color(dayuan.color.r, dayuan.color.g, dayuan.color.b, 0.3f);
    xiaoyuan.color = new Color(xiaoyuan.color.r, xiaoyuan.color.g, xiaoyuan.color.b, 0.3f);
}

// Update is called once per frame
void Update()
{

}

private void MyPress(Vector2 v2)
{
    Vector2 shouzhiPos;
    RectTransformUtility.ScreenPointToLocalPointInRectangle(GameManager.instance.cv.transform as RectTransform, v2, GameManager.instance.cv.worldCamera, out shouzhiPos);
    float dis = Vector3.Distance(shouzhiPos, dayuan.transform.localPosition);
    dis = Mathf.Clamp(dis, 0, dayuan.rectTransform.rect.width / 2);
    Vector3 shouzhiV3 = shouzhiPos;
    Vector3 dir = (shouzhiV3 - dayuan.transform.localPosition).normalized;
    xiaoyuan.transform.localPosition = dayuan.transform.localPosition + dir * dis;

    direction = dir * dis / (dayuan.rectTransform.rect.width / 2);

    dayuan.color = new Color(dayuan.color.r, dayuan.color.g, dayuan.color.b, 1);
    xiaoyuan.color = new Color(xiaoyuan.color.r, xiaoyuan.color.g, xiaoyuan.color.b, 1);
}

private void MyUp()
{
    xiaoyuan.transform.localPosition = dayuan.transform.localPosition;
    dayuan.color = new Color(dayuan.color.r, dayuan.color.g, dayuan.color.b, 0.3f);
    xiaoyuan.color = new Color(xiaoyuan.color.r, xiaoyuan.color.g, xiaoyuan.color.b, 0.3f);
    direction = Vector3.zero;

}

public void MyEndDrag()
{
    MyUp();
}

public void OnPointerDown(PointerEventData eventData)
{
    MyPress(eventData.pressPosition);
}

public void OnPointerUp(PointerEventData eventData)
{
    MyUp();
}

public void OnDrag(PointerEventData eventData)
{
    MyPress(eventData.position);
}

public void OnEndDrag(PointerEventData eventData)
{
    MyUp();
}
}

标记====》大圆(dayuan)就是摇杆外部的园   小圆(xiaoyuan)摇杆内部的圆

你可能感兴趣的:(unity,Unity黑科技实验室)