unity实现UGUI的摇杆

游戏摇杆是一个比较常用的UI功能,通过摇杆的操作,获得UI界面输入的方向和力度。unity自身的UGUI 系统并没有自带这个输入空间。另外也有一些Unity摇杆插件(例如EasyTouch),但是引入第三方插件会新增许多不必要的代码,增加项目的复杂度。

GGUI实现摇杆功能也非常简单。主要思路是实现对摇杆的GameObject实现 IPointerDownHandler,IPointerUpHandler,IDragHandler 三个接口,鼠标按下,拖动,弹起事件。根据得到的开始点位置和结束点位置计算方向向量。

UI界面结构

屏幕快照-2019-04-07-下午9.50.05.png

JoyStick对象作为摇杆的背景图片,Center对象作为摇杆的中心。把以下脚本挂载到JoyStick对象上,JoyStick对象接受事件输入。

摇杆代码

Joystick实现UGUI事件输入的三个接口,在OnDrag中计算起始点到结束的的方向单位向量moveDir中,摇杆的力度记录到moveLen(0-1)中。

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

/// <summary>
/// UGUI游戏摇杆
/// </summary>
public class Joystick :MonoBehaviour ,IPointerDownHandler,IPointerUpHandler,IDragHandler
{

    public static Joystick Instance = null;

    public Transform centerTrans;
    public Vector2 moveDir=Vector2.zero;
    public float moveLen = 0;
    public bool isDraging = false;

    private float MaxMoveLen = 125;

    protected float mRadius=0f;

    void Awake(){
        Instance = this;
    }

    public  void Start()
    {
        //计算摇杆块的半径
        MaxMoveLen = (transform as RectTransform).sizeDelta.x * 0.5f;
    }

    public  void OnPointerDown(PointerEventData data){
        //Debug.Log ("OnBeginDrag");
        isDraging = true;
    }
    public  void OnDrag (PointerEventData eventData)
    {
        
        Vector2 v2Pos = eventData.position;
        Vector3 v3Pos= Camera.main.ScreenToWorldPoint(new Vector3(v2Pos.x,v2Pos.y,0f)); //屏幕坐标转世界坐标
        v3Pos.z = 0;
        Vector3 localPos = transform.worldToLocalMatrix.MultiplyPoint (v3Pos); //世界坐标 转本地坐标
        localPos.z = 0;

    
        moveDir.x = localPos.x;
        moveDir.y = localPos.y;
        moveDir.Normalize (); //摇杆方向

        float len = localPos.magnitude;
        if (len > MaxMoveLen)
            len = MaxMoveLen;

        moveLen = len / MaxMoveLen;  //摇杆力度

        Vector3 pointPos = localPos.normalized*len;
        centerTrans.localPosition = pointPos;
    }

    public  void OnPointerUp(PointerEventData data){
        //Debug.Log ("OnEndDrag");
        isDraging = false;
        centerTrans.localPosition = Vector3.zero;
    }
}

更多unity2018的功能介绍请到paws3d爪爪学院查找。链接https://www.paws3d.com/,也可以加入unity学习讨论群935714213

近期更有资深开发人士直播分享unity开发经验,详情请进入官网或加入QQ群了解

猜你喜欢

转载自blog.csdn.net/qq_35037137/article/details/89092590