【Unity-UGUI】用UGUI實現遊戲搖桿

轉載自雨鬆MOMO大神的文章,只爲學習與知識分享。本人稍做了修改,使Player腳本更方便使用搖桿數值。雨鬆MOMO原文

它的原理就是利用ScrollRect來限制搖塊的搖動區域,ScrollRect是矩形的,搖桿的搖動區域應該是個圓形。

ScrollCircle就是搖桿的背景, 裏面的Image就是搖塊。

效果如下:

代碼如下:

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

public class ScrollCircle : ScrollRect {

    protected float mRadius = 0f; 
    protected override void Start()
    {
        base.Start();
        //計算搖桿塊的半徑
        mRadius = (transform as RectTransform).sizeDelta.x * 0.5f;
    }
    public override void OnDrag(PointerEventData eventData)
    {
        base.OnDrag(eventData);
        var contentPostion = this.content.anchoredPosition;
        if (contentPostion.magnitude > mRadius)
        {
            contentPostion = contentPostion.normalized * mRadius;
            SetContentAnchoredPosition(contentPostion);
        }
        YHEasyJoystick.Instance.JoystickTouch = contentPostion;
    }
    public override void OnEndDrag(PointerEventData eventData)
    {
        base.OnEndDrag(eventData);
        YHEasyJoystick.Instance.JoystickTouch = Vector2.zero;
    }
}
public class YHEasyJoystick
{
    private static YHEasyJoystick instance;
    public static YHEasyJoystick Instance
    {
        get
        {
            if (null == instance)
                instance = new YHEasyJoystick();
            return instance;
        }
        set { instance = value; }
    }
    public Vector2 JoystickTouch { get; set; }
}




實例:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test2222 : MonoBehaviour {

    private Transform mPlayer;
    private float moveSpeed = 2;
    private float mPlayerPx = 0;
    private float mPlayerPz = 0;
    private void Start()
    {
        mPlayer = transform;
    }
    private void Update () {
        if (mPlayer == null) return;
        mPlayerPx = YHEasyJoystick.Instance.JoystickTouch.x;
        mPlayerPz = YHEasyJoystick.Instance.JoystickTouch.y;
        if (mPlayerPx != 0 || mPlayerPz != 0)
        {
            Debug.Log(YHEasyJoystick.Instance.JoystickTouch);
            Quaternion wantRotation = Quaternion.LookRotation(new Vector3(mPlayerPx, 0, mPlayerPz));
            Quaternion dampingRotation = Quaternion.Lerp(mPlayer.rotation, wantRotation, 10f * Time.deltaTime);
            mPlayer.rotation = dampingRotation;
            mPlayer.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
        }
	}
}

注意:如果你發現搖桿會被其他UGUI遮擋,本人的處理辦法如下。

在此感謝雨鬆MOMO大神的研究分享,受益匪淺!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章