【Unity-UGUI】用UGUI实现游戏摇杆

转载自雨松MOMO大神的文章,只为学习与知识分享。本人稍做了修改,使Player脚本更方便使用摇杆数值。雨松MOMO原文

它的原理就是利用ScrollRect来限制摇块的摇动区域,ScrollRect是矩形的,摇杆的摇动区域应该是个圆形。

ScrollCircle就是摇杆的背景, 里面的Image就是摇块。

效果如下:

【Unity-UGUI】用UGUI实现游戏摇杆_第1张图片

【Unity-UGUI】用UGUI实现游戏摇杆_第2张图片

代码如下:

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遮挡,本人的处理办法如下。

【Unity-UGUI】用UGUI实现游戏摇杆_第3张图片

在此感谢雨松MOMO大神的研究分享,受益匪浅!

你可能感兴趣的:(unity3d,UGUI)