天天看點

Unity3d使用UGUI開發原生虛拟搖杆之美

在Unity3d中開發虛拟搖杆方式有比較多,可以使用EasyTouch、FairyGUI等插件來開發。本文給大家介紹使用Unity3d的原生UGUI來開發出自己的虛拟搖杆,這樣可以減少遊戲資源包的大小。

先展示下效果圖:

Unity3d使用UGUI開發原生虛拟搖杆之美

現在開發我們的開發

建立一個Image1,并且在Image1建立一個子對象Image2

在Image1中挂載一個自定義腳本,這裡我命名為Joystick

腳本代碼如下

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
 
public class Joystick : ScrollRect
{
    private float mRadius;
    public System.Action<RectTransform> JoystickMoveHandle;
    public System.Action<RectTransform> JoystickEndHandle;
 
    protected override void Start()
    {
        mRadius = this.GetComponent<RectTransform>().sizeDelta.x * 0.5f;
        this.content.gameObject.SetActive(false);
    }
 
 
    public override void OnDrag(PointerEventData eventData)
    {  
        base.OnDrag(eventData);
        this.content.gameObject.SetActive(true);
 
        //虛拟搖杆移動
        var contentPostion = this.content.anchoredPosition;        
        if (contentPostion.magnitude > mRadius)
        {
            contentPostion = contentPostion.normalized * mRadius;
            SetContentAnchoredPosition(contentPostion);
        }
        //旋轉
        if (content.anchoredPosition.y != 0)
        {
            content.eulerAngles = new Vector3(0, 0, Vector3.Angle(Vector3.right, content.anchoredPosition) * content.anchoredPosition.y / Mathf.Abs(content.anchoredPosition.y) - 90);
        }
 
    }
 
    private void FixedUpdate()
    {
        if (this.content.gameObject.activeInHierarchy)
        {
            if (JoystickMoveHandle != null)
            {
                JoystickMoveHandle(this.content);
            }
        }
    }
 
    public override void OnEndDrag(PointerEventData eventData)
    {
        base.OnEndDrag(eventData);
 
        this.content.gameObject.SetActive(false);
 
        if (JoystickEndHandle != null)
        {
            JoystickEndHandle(this.content);
        }
    }
}
           

然後将Image2拖動到content屬性變量裡

Unity3d使用UGUI開發原生虛拟搖杆之美

這樣就可以移動并且拖動我們的虛拟搖杆了

接下來要讓我們的遊戲主角跟随我們的搖杆移動而移動

在我們的主角兒挂載一個自定義腳本

在Start方法裡添加代碼:

mJoystick = GameObject.Find("Joystick").GetComponent<Joystick>();
            mJoystick.JoystickMoveHandle = JoystickHandle;
            mJoystick.JoystickEndHandle = JoystickEndHandle;           
transform.eulerAngles = new Vector3(0, -content.eulerAngles.z, 0);
                transform.Translate(Vector3.forward * Time.deltaTime * mMoveSpeed);