unity使用UGUI创建摇杆

1.现在unity做一个项目,各种插件各种包,于是项目资源就无限变大了,其实一些简单的功能可以自己写,这里就是试着使用UGUI编写一个摇杆功能

2.脚本如下:

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

public class UGUIJoystick : MonoBehaviour,IDragHandler{

    public RectTransform joystickImage;
    public Vector3 startPos;
    public int maxDis = 70;
    public float speed = 5;

	// Use this for initialization
	void Start () {
        startPos = joystickImage.position;
	}
	
	// Update is called once per frame
	void Update () {

        if (Application.platform == RuntimePlatform.Android)
        {
            if (Input.touchCount <= 0)
            {
                if (Vector3.Distance(joystickImage.position, startPos) > 0.01f)
                {
                    joystickImage.position = joystickImage.position - (joystickImage.position - startPos).normalized * speed;
                }
            }
        }
        else
        {
            if (!Input.GetMouseButton(0))
            {
                if (Vector3.Distance(joystickImage.position, startPos) > 0.01f)
                {
                    joystickImage.position = joystickImage.position - (joystickImage.position - startPos).normalized * speed;
                }
            }
        }

	}

   public void OnDrag(PointerEventData eventData)
    {
        Vector3 wordPos;
        //将UGUI的坐标转为世界坐标
        if (RectTransformUtility.ScreenPointToWorldPointInRectangle(joystickImage, eventData.position, eventData.pressEventCamera, out wordPos))
            joystickImage.position = wordPos;

        Vector3 dir = (joystickImage.position - startPos).normalized;
        if (Vector3.Distance(joystickImage.position, startPos) >= maxDis)
        {
            joystickImage.position = startPos + dir * maxDis;
        }
    }
}

3.这里除了一个简单的接口实现,就是坐标的转换,让摇杆一直跟着手指移动,这里就需要一个函数RectTransformUtility.ScreenPointToWorldPointInRectangle

4.将这个脚本绑定在摇杆用于移动的图片上,效果如下:


5.摇杆常用移动端,但是我并未在移动端测试

原文地址:https://www.cnblogs.com/liang123/p/6325891.html